【问题标题】:Promise plus number returns promise承诺加数字返回承诺
【发布时间】:2018-02-12 12:51:48
【问题描述】:

我有一个简单的代码

async function foo() {
  const b = bar()
  return 2 + b
}

async function bar() {
  return 2
}

(async() => {
  console.log(typeof foo())
})()

它记录object。不是NaNnumber + object -> object 是怎么发生的?

根据我对+ 规范的记忆,如果其中一个操作数是基元,第二个是对象,则应将对象转换为基元。在这种情况下使用.valueOf() 方法

【问题讨论】:

  • 它将两个值连接为“2[object Promise]”。只需省略类型
  • foo 是一个 async function,调用它 (foo()) 将返回一个显然是一个对象的承诺。
  • 想想“事物的类型”与“事物返回的类型”,在这种情况下你会得到第一个。无论您是在卡车上拖啤酒或水果,还是只是步行,道路仍然是一条道路。

标签: javascript promise type-conversion


【解决方案1】:

它认为这是因为async 函数在您的情况下尚未解决,因为没有await。所以你得到的是 promise 对象而不是你的结果。

查看这些案例:

async function foo () {
    const b = await bar() //await result
    return 2 + b
}

async function bar () {
    return 2
}

;(async () => {
    console.log(typeof await foo()) //number
})()

async function foo () {
    const b = bar() //no await
    return 2 + b
}

async function bar () {
    return 2
}

;(async () => {
    console.log(typeof await foo()) //string
})()

【讨论】:

    【解决方案2】:

    函数foobar 返回一个promise,所以,你得到的类型是promise (Object)

    可能你想比较结果,所以需要等待promise解析连接:

    let result = await foo();
                 ^
    

    async function foo() {
      const b = bar() // Here you need to wait as well.
      return 2 + b; // 2 + "[object Promise]"
    }
    
    async function bar() {
      return 2
    }
    
    (async() => {
      let result = await foo();
      console.log(result);
      console.log(typeof result);
    })()

    现在,要获取您需要转换为数字的 NaN 值:

    async function foo() {
      const b = bar();  // Here you need to wait as well.
      return Number(2 + b); // <- Try to conver to number
    }
    
    async function bar() {
      return 2
    }
    
    (async() => {
      let result = await foo();
      console.log(result);
      console.log(typeof result);
    })()

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 2023-01-27
      • 2015-11-27
      • 2017-12-21
      相关资源
      最近更新 更多