[英]Javascript array.push in Promise.all returning undefined
I have a promise and I'm pushing a value to Promise.all but it's returning undefined. 我有一个承诺,我正在向Promise.all推送一个值,但它返回的是不确定的。
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 您的Promises实现不正确,请参阅此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 另外,您正在犯语法错误,例如arr.push应该在
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. Promise.all接受一个数组,而您正在做的就是用另一个数组包装一个数组。
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]
因此,
arr = [undefined]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.