I have a promise and I'm pushing a value to Promise.all but it's returning undefined.
Here's the code:
var arr = []; var mypromise = new Promise((resolve, reject) => { resolve('mypromise'); arr.push(mypromise); }); Promise.all([arr]).then(values => { console.log(values); });
How can I fix this?
var arr = []; var mypromise = new Promise((resolve, reject) => { resolve('mypromise'); }); arr.push(mypromise); Promise.all(arr).then(values => { console.log(values); });
Your Implementation for Promises is not proper, refer this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Also, you are making syntax mistakes like arr.push should be after
var mypromise = new Promise((resolve, reject) => { resolve('mypromise'); });
and Promise.all accepts an array and what you are doing is wrapping an array with another array.
var arr = [];
var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
arr.push(mypromise);
});
Promise.all([arr]).then(values => {
console.log(values);
});
I'll point out to you a mistake you made in your code...
var arr = []; // arr is currently an empty array
// when you create a variable mypromose, it is also currently undefined
var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
// even till now mypromise is undefined
// what you are doing is arr.push(undefined)
arr.push(mypromise);
});
// after it is completed, mypromise is now defined...
Hence, arr = [undefined]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.