最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to resolve a promise with two values? - Stack Overflow

programmeradmin9浏览0评论

Consider the following code:

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

It outputs

a undefined

How can I resolve return the two values out of the Promise?

Consider the following code:

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

It outputs

a undefined

How can I resolve return the two values out of the Promise?

Share Improve this question asked Aug 31, 2018 at 13:54 TSRTSR 20.8k32 gold badges120 silver badges240 bronze badges 2
  • 2 With an array ? – Luca Kiebel Commented Aug 31, 2018 at 13:55
  • or object... ;-) – Lyubomir Commented Aug 31, 2018 at 13:56
Add a ment  | 

3 Answers 3

Reset to default 6

Return them in an array.

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

You cannot, a promise fulfills or rejects with exactly one value.

It's trivial however to put the two values in a structure, such as an array:

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

It outputs

a b
发布评论

评论列表(0)

  1. 暂无评论