与承诺解析相关的输出

huangapple go评论66阅读模式
英文:

Output related to promise resolution

问题

代码的输出是:

1
2
3

我的问题是为什么数据的值是3,而不是状态为已完成的Promise?

我期望data包含一个Promise而不是数字3。

英文:
function somePromise () {
    return new Promise (resolve => {
        setTimeout(() => {
            resolve (3)
        }, 3000)
    })
}
async function solve() {
    console.log(1) 
    let data = await somePromise(); 
    console.log(2) 
    console.log(data)
}
solve();

The output for this code is:

>1
>2
>3

My question is why is the value of data 3 and not the promise with state as fulfilled ?

I expected data to have a Promise and not the number 3.

答案1

得分: 2

使用await关键字在表达式中的目的是使该表达式评估为Promise的已解析值,而不是Promise本身

英文:

The point of using the await keyword in an expression is to have that expression evaluate as the resolved value of a promise instead of as the promise itself.

huangapple
  • 本文由 发表于 2023年6月26日 23:01:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76557892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定