繁体   English   中英

异步 JavaScript 执行顺序?

[英]Asynchronous JavaScript execution order?

异步JS对我来说一直有点混乱......

我有这个示例代码:

function asyncFunction() {
    return new Promise(function(resolve, reject) {
        resolve([1, 2, 3, 4, 5])
    })
};

function example() {
    asyncFunction().then(
        output => {
            for (element of output) {
                console.log(element + ", A") //This should be displayed first
            }
        }
    )
};

example();

console.log('B'); //But it isn't

产生以下输出:

B
1, A
2, A
3, A
4, A
5, A

有没有办法对此进行编程,以便在 As 之后打印 B? 我实际上在这里使用了一个 RSS 提要解析器模块,上面只是一个例子来说明问题。

调用asyncFunction返回一个 Promise。 即使承诺立即解决,任何.then小号链式到它会被放入队列microtask,其任务将只开始运行,一旦所有其它同步代码已经完成。

由于console.log('B'); example调用之后同步运行, B将在.then回调运行之前打印。

如果你想确保所有的数组元素记录B之后得到记录,返回asyncFunction从承诺example ,然后调用.then它,并记录B内部的.then的回调:

 function asyncFunction() { return new Promise(function(resolve, reject) { resolve([1, 2, 3, 4, 5]) }) }; function example() { return asyncFunction().then( output => { for (element of output) { console.log(element + ", A") //This should be displayed first } } ) }; example().then(() => { console.log('B'); //But it isn't });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM