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

Consider the following code:new Promise(function (res, rej) {res('a','b')}).then(f

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744240053a4564662.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信