异步JavaScript执行顺序?

Tee*_*1er 2 javascript asynchronous

异步 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
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

B
1, A
2, A
3, A
4, A
5, A
Run Code Online (Sandbox Code Playgroud)

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

Cer*_*nce 5

调用asyncFunction返回一个 Promise。即使 Promise 立即解析,.then链接到它的任何 s 都会被放入微任务队列中,只有在所有其他同步代码完成后,微任务队列的任务才会开始运行。

由于在调用console.log('B');后同步运行exampleB因此将在回调运行之前打印.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
});
Run Code Online (Sandbox Code Playgroud)