Node.js:异步等待(带有/不带有Promise)

时间:2019-10-01 17:19:39

标签: javascript node.js async-await

当我为我的项目实现一些逻辑原型时,我注意到async-await和Promise的一些有趣行为。

// Notice this one returns a Promise
var callMe = function(i) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(i)
            resolve(`${i} is called :)`)
        }, (i+1)*1000)
    })  
}

// But this one doesn't
var callYou = function(i) {
    setTimeout(() => {
        console.log(i)
    }, (i+1)*1000)
}

async function run() {
    console.log("Start")
    for(let i = 0; i < 3; i++) {
        let val = await callYou(i)
         # also try with callMe()
         #let val = await callMe(i)
        console.log(val)
    }
    console.log("End")
}

run()

使用let val = await callYou(i),结果看起来像这样

Start
callYou()
callYou()
callYou()
End
0
1
2

而对于let val = await callMe(i),结果看起来像这样

Start
0
0 is called :)
1
1 is called :)
2
2 is called :)
End

我期望两个函数的行为类似,因为异步函数本质上会返回一个promise。有人可以说明为什么会这样吗?

1 个答案:

答案 0 :(得分:0)

async函数返回承诺,但是callYoucallMe都不是async函数,即使它们在哪里,当函数不返回callYou时也将实现当回调传递给setTimeout函数时执行。