首页 > 解决方案 > resolve 在 Promise 中真正做了什么?

问题描述

我以为我对 Node 和 Promises 有很好的理解,但是当我试图为我的朋友解释一些事情时,我遇到了这个问题。

我的问题是,这个小脚本的预期输出是什么?

const myPromise = new Promise((resolve, reject) => {
    console.log("inside promise")
    resolve("Lol!")

})

for (let i=0; i<1000000; i++) {}
// just want to be sure that the next line starts after the promise finishes execution

myPromise.then(() => console.log("then!"))

console.log("finished")

我的预期输出:

inside promise
finished

我的想法是,如果承诺在读取之前完成执行myPromise.then(...,那么日志不应该永远不会出现吗?

实际输出:

inside promise
finished
then!

如果我发出resolve("Lol!")尽管预期输出与实际输出匹配。

谁能解释一下这里发生了什么?

谢谢!

标签: javascriptnode.jsasynchronous

解决方案


这是您的示例注释:

console.log('Before myPromise is created');

const myPromise = new Promise((resolve, reject) => {
    // This is executed immediately when a new
    // Promise is created, so it will appear
    // BEFORE 'After myPromise is created'.
    console.log("Inside promise")
   
    // This passes the value "Lol!" to
    // the 'then' function. By itself it
    // does not console log anything.
    resolve("Lol!")
})

console.log('After myPromise is created');

// This does nothing, code immediately
// carries on executing. After >=100ms a function
// doing nothing is called.
setTimeout(() => {}, 100)

// The 'then' is passed the argument of
// `resolve()` (in this case "Lol!")
myPromise.then(resolveArg => console.log(resolveArg))

// Second to last console log because
// all .then() handlers are called asynchronously
// once the main thread is idle (as the Promises/A+
// spec says, when the JS engine returns back to 
// "platform code"). Therefore "Lol!" will be the 
// last thing logged.
console.log("Finished")


推荐阅读