Promise和for循环问题,循环需要上一次的结果
场景是这样的,需要计算工序的时间,有开始时间,结束时间,下一道工序的开始的时间是上一道工序的结束时间,请问这种用promise和for循环怎么处理,谢谢大家帮忙!
如果我没有理解错的话,可以在promise外部生命变量,然后再promise.then里面就可以拿到该变量了,可以设计成数组,记录对应工序和耗时
试试Promise.map
呢
可以结合reduce
var arr = [1, 2, 3, 4, 5, 6];
var p = (val) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(val);
return resolve(val)
}, 1000);
})
};
var run = (arr) => {
return arr.reduce((chain, val) => {
console.log('reduce', chain, val);
return chain.then(() => {
return p(val)
});
}, Promise.resolve())
.then(() => {
console.log('done')
})
}
run(arr);
doJob = (runTime,start) => new Promise(resolve => setTimeout(() => resolve((console.log(runTime + start), runTime + start)), runTime)); […Array(5).keys()].reduce((job) => job.then(startTime => doJob(1000, startTime)), Promise.resolve(Date.now()))
// 4 获取terms // 遍历每一个grades,然后获取下面的terms,合并到grades let forGrades = async function(grades) { for(let grade of grades){ await cc.getTerms(grade.grade_id, 1).then(result => { grade.terms = result; }); } }
await forGrades(grades);
谢谢各位的帮助,我已经写出来了,代码如下:
var result = $q.resolve({
operationTimes: [],
startTime: startTime
});
for (var i = 0, len = operations.length; i < len; i++) {
(function(i) {
result = result.then(function(obj) {
if (obj.startTime) {
return getPlanStartDate(obj.startTime, mo.Qty, operations[i], i, obj.operationTimes);
}
});
})(i)
}
result.then(function(obj) {
console.log(obj.operationTimes);
}).catch(function(err) {
console.log(err);
});