resolve在promises中到底做了什么?



我认为我对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!"),虽然预期输出与实际输出匹配。

谁能给我解释一下这里发生了什么事?谢谢!

下面是你的例子:

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")

JS promise提供了异步运行代码的选项。因此,您向JS引擎发出信号,表示希望在另一个操作完成后执行一个操作。由于行动可以成功或不成功,承诺可以解决(resolve)或拒绝(reject)。如果处理成功,使用then;如果处理失败,使用catch;如果处理失败,可以使用finally

所以当你声明一个承诺时,JS引擎知道它不是你现在需要的东西,而是以后。它将开始执行,但稍后将与其结果相关。在启动promise操作之后,它将运行其余的同步命令,在你的情况下,除了then。一旦完成,它将检查它是否有已经解决的承诺,如果是,它将执行相关的than

resolve()将承诺的then放入回调队列。稍后,当调用堆栈为空时,引擎将处理它。reject()也一样,但catch

如果你想保持一个更干净的语法,我建议检查async-await。

*也注意你的setTimeout没有给你任何东西。如果你把console.log放在里面,它也只会在'finish'后面显示。

new Promise()处理必须"等待"的操作,然后将结果返回给then ()命令—这是一个异步操作。考虑下面的例子:

const myPromise = (val1, val2) => {
return new Promise((resolve, reject) => {
val1 > val2 
? setTimeout(() => resolve("LOL !!!"), 1500)
: reject(""val2" is greater than "val1"");
});    
}
// Then you call:
myPromise(5, 1).then(
// Processing results:
function (result) {
console.log("This is result: ", result);
},

// Error handling from "reject()"
function(error) {
console.log("This is an error: ", error);
}
)
// error case:
myPromise(1, 5).then(
// Processing results:
function (result) {
console.log("This is result: ", result);
},

// Error handling from "reject()"
// the result in console.log will be first than in the case of resolve()
function(error) {
console.log("This is an error: ", error);
}
)
// Error handling with 'catch' block
myPromise(1,5)
.then((result) => console.log(result))
.catch((err) => console.log("This is error: ", err, "# with catch-block"))

相关内容

  • 没有找到相关文章

最新更新