以下面为例:
function sayHello () {
return new Promise( function(resolve, reject) {
console.log('Were inside the promise');
return resolve(5);
})
}
sayHello().then(function(success){
console.log(success)
})
console.log('Im outside the promise')
我们知道它按以下顺序执行:
Were inside the promise
Im outside the promise
5
然后,对于类似的事情:
function sayHello () {
return new Promise( function(resolve, reject) {
console.log('Were inside the promise');
return resolve((function(){
return 5
})());
})
}
sayHello().then(function(success){
console.log(success)
})
console.log('Im outside the promise')
它返回与前一个示例相同的 console.log
输出序列。太棒了,有道理;无论resolve中的值是什么,当then()
执行时,都会作为参数通过管道传输。
为什么,当我有类似下面的内容时:
function sayHello () {
return new Promise( function(resolve, reject) {
console.log('Were inside the promise');
return resolve(console.log(5));
})
}
sayHello().then(function(success){
console.log(success)
})
console.log('Im outside the promise')
我收到这个订单了吗:
Were inside the promise
5
Im outside the promise
最佳答案
当解析器函数在下一个“tick”中被调用时,它的参数会立即被评估。这就是为什么您会在第三个代码段示例中看到 console.log(5)
在 before then
回调执行。如果您将第二个代码片段更改为:
function sayHello() {
return new Promise(function(resolve, reject) {
console.log('Were inside the promise');
return resolve((function() {
console.log('Inside resolver argument');
return 5
})());
})
}
sayHello().then(function(success) {
console.log(success)
});
console.log('Im outside the promise');
关于javascript - 为什么 console.log() 在 Promises 的resolve() 函数中立即执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49916466/