循环里多个异步串行运行方法
for 循环
const items = [3000, 2000, 1000, 4000];
const testPromise = (param) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(
`时间(s):${Math.floor(Date.now() / 1000)},结果:${param} `
);
resolve();
}, param);
});
};
(async () => {
console.log(`开始时间(s):${Math.floor(Date.now() / 1000)}`);
for (let item of items) {
await testPromise(item);
}
console.log(`结束时间(s):${Math.floor(Date.now() / 1000)}`);
})();
reduce 方法
const items = [3000, 2000, 1000, 4000];
const testPromise = (param) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(
`时间(s):${Math.floor(Date.now() / 1000)},结果:${param} `
);
resolve();
}, param);
});
};
(async () => {
console.log(`开始时间(s):${Math.floor(Date.now() / 1000)}`);
const result = items.reduce((resPromise, next) => {
return resPromise.then(() => {
return testPromise(next);
});
}, Promise.resolve());
result.then(() => {
console.log(`结束时间(s):${Math.floor(Date.now() / 1000)}`);
});
})();
这里异步生成器的方法,但是实现不是很简约,就不展示了!
多个异步并行运行方法
这里使用 promise.all()
const items = [3000, 2000, 1000, 4000];
const testPromise = (param) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log(
`时间(s):${Math.floor(Date.now() / 1000)},结果:${param} `
);
resolve();
}, param);
});
};
(async () => {
const promises = items.map((item) => {
return testPromise(item);
});
await Promise.all(promises);
})();
评论 (0)