我有一个承诺,我正在向Promise.all推送一个值,但是它返回的是未定义的。
代码如下:
var arr = [];
var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
arr.push(mypromise);
});
Promise.all([arr]).then(values => {
console.log(values);
});
我该如何解决?
答案 0 :(得分:3)
var arr = [];
var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
});
arr.push(mypromise);
Promise.all(arr).then(values => {
console.log(values);
});
您的承诺实现不正确,请参阅此 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
此外,您正在犯语法错误,例如arr.push应该在
之后var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
});
Promise.all都接受一个数组,而您正在做的就是将一个数组包装到另一个数组中。
答案 1 :(得分:1)
var arr = [];
var mypromise = new Promise((resolve, reject) => {
resolve('mypromise');
arr.push(mypromise);
});
Promise.all([arr]).then(values => {
console.log(values);
});
我会向您指出您在代码中犯的一个错误...
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...
因此,arr = [undefined]