这是我的Javascript编码.我认为结果是1 2 3 4 5.
async function fn1 () {
console.log(1);
await fn2();
console.log(3);
};
async function fn2 () {
console.log(2);
};
fn1();
new Promise((resolve, reject) => {
console.log(4)
resolve()
}).then(() => {
console.log(5)
})Run Code Online (Sandbox Code Playgroud)
但.结果是:1 2 4 5 3.
// functions declaration
async function fn1 () {
console.log(1);
await fn2(); // wait for async function fn2(which gets dispatched on thread 3) => so console.log(2) should be here chronologically
console.log(3);
};
async function fn2 () {
console.log(2);
};
// thread 1 starts (the actual execution code)
fn1(); // since fn1 is async it gets dispatched on thread 2
new Promise((resolve, reject) => {
console.log(4)
resolve() // trigger () => {console.log(5)}
}) // promise declaration
.then(() => {
console.log(5)
}) // execute the promise right awayRun Code Online (Sandbox Code Playgroud)
简单来说,如果console.log(1),console.log(2),console.log(3)发生在一个线程按时间顺序,console.log(4),console.log(5)发生在其他线程上按时间顺序.它们相互交叉.
附注: JavaScript本身是单线程的,不支持多线程!(除了web worker等,在我们的"async"上下文中)我简化了很多并在thread这里使用这个术语只是为了让它易于理解.为了不误解您的异步操作概念,如果您不确定异步操作如何在JavaScript中,我建议您阅读此QnA.
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |