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
3 Answers
Reset to default 6Return 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条)