进入条件块后,假设没有异步操作改变条件是否安全?
Upon entering a conditional block, is it safe to assume no async action changed the condition?
在这个例子中,我想要 return 一个未决的 "stop" Promise (1),它删除实例对自身的引用 (1),并且被调用者可能有未决/排队的操作。
如果当前正在停止,我想return那个现有的、未决的承诺。
我的问题是初始条件是否是确定性的并且它总是 return 一个 Promise;不是未定义的。
由于变量/引用在完成时被删除,我很好奇异步操作是否可以在条件语句和 return 语句之间 "jump in",或者这是否被块执行禁止/优先.
谢谢
stop () {
if (this.awaitStop) {
return this.awaitStop;
} else {
this.awaitStop = NativeDevice.video.stop(); // Promise
return this.awaitStop.then(() => delete this.awaitStop);
}
}
Non-async 函数不会被中断。任何回调只会在所有函数返回并且控制流 returns 到 "event loop".
后执行
如果你有一个异步函数,事情就会不同:
async function f() {
if (foo) {
await bar(); // This interrupts f and lets any other code run.
console.log(foo); // foo may or may not be the same as before.
}
}
JavaScript 有 Run-To-Completion semantic, and is not multi-threaded in the conventional manner, as a standalone language (see here for examples where this could break depending on the environment).
对于此示例,Run-To-Completion 意味着所有同步代码将 运行 直到完成并且不能被任何异步调用中断。
只有 generators (with yield
) and async functions (with await
) can cause interuptions in JS and this has to be done explicitly (non-preemptive multitasking).
由于您的代码中两者都没有,因此您的条件将确定性地运行。
在这个例子中,我想要 return 一个未决的 "stop" Promise (1),它删除实例对自身的引用 (1),并且被调用者可能有未决/排队的操作。
如果当前正在停止,我想return那个现有的、未决的承诺。
我的问题是初始条件是否是确定性的并且它总是 return 一个 Promise;不是未定义的。
由于变量/引用在完成时被删除,我很好奇异步操作是否可以在条件语句和 return 语句之间 "jump in",或者这是否被块执行禁止/优先.
谢谢
stop () {
if (this.awaitStop) {
return this.awaitStop;
} else {
this.awaitStop = NativeDevice.video.stop(); // Promise
return this.awaitStop.then(() => delete this.awaitStop);
}
}
Non-async 函数不会被中断。任何回调只会在所有函数返回并且控制流 returns 到 "event loop".
后执行如果你有一个异步函数,事情就会不同:
async function f() {
if (foo) {
await bar(); // This interrupts f and lets any other code run.
console.log(foo); // foo may or may not be the same as before.
}
}
JavaScript 有 Run-To-Completion semantic, and is not multi-threaded in the conventional manner, as a standalone language (see here for examples where this could break depending on the environment).
对于此示例,Run-To-Completion 意味着所有同步代码将 运行 直到完成并且不能被任何异步调用中断。
只有 generators (with yield
) and async functions (with await
) can cause interuptions in JS and this has to be done explicitly (non-preemptive multitasking).
由于您的代码中两者都没有,因此您的条件将确定性地运行。