【问题标题】:How to resolve a promise with two values?如何解决具有两个值的承诺?
【发布时间】:2018-08-31 21:58:00
【问题描述】:

考虑以下代码:

new Promise(function (res, rej) {
    res('a','b')
}).then(function (a, b) {
    console.log(a,b)
})

输出

a undefined

如何解决从 Promise 中返回两个值?

【问题讨论】:

  • 带数组?
  • 或对象... ;-)

标签: javascript node.js asynchronous promise


【解决方案1】:

以数组的形式返回它们。

new Promise((res, rej) => {
  res(["a", "b"]);
}).then(([a, b]) => {
  console.log(a, b);
});

【讨论】:

    【解决方案2】:

    你不能,一个 Promise 只用一个值实现或拒绝。

    不过,将这两个值放在一个结构中很简单,比如数组:

    new Promise(function(resolve) {
        resolve(['a','b'])
    }).then(function([a, b]) { // array destructuring
        console.log(a, b)
    })
    

    【讨论】:

      【解决方案3】:
      new Promise(function (res, rej) {
          res(['a','b'])
      }).then(function (resContent) {
          console.log(...resContent)
      })
      

      输出

      a b
      

      【讨论】:

        猜你喜欢
        • 2020-08-14
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 2020-09-07
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        相关资源
        最近更新 更多