promise 循环执行获取不到值?
const list = [];
for (let i = 0; i < 100; ++i) {
list.push(i+'c');
}
var promise = new Promise(function (resolve, reject) {
setTimeout(function () {
console.log('3秒');
return resolve('3秒');
}, 3000);
});
function PromiseForEach(arr, cb) {
let realResult = []
let result = Promise.resolve()
arr.forEach(function (a, index) {
result = result.then(function () {
return cb(a).then(function (res) {
realResult.push(res);
});
});
});
return result.then(function () {
return realResult;
});
}
promise.then(function (d) {
PromiseForEach(list, function (number) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log(number);
return resolve(number);
}, 100);
});
})
}).then(function (data) {
console.log("成功");
console.log(data);
}).catch(function (err) {
console.log("失败");
console.log(err);
});
//预期的打印结果是
//3秒
// console.log(number);
//成功
//data
//然而实际的打印结果是
//3秒
//成功
//undefined
//最后执行了 console.log(number);
2 回复
@yinxin630 谢谢啊加上return就好了
return PromiseForEach(list, function (number) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
console.log(number);
return resolve(number);
}, 100);
});
})