function sleepPromise(msg, t) {
return new Promise((resolve) => {
setTimeout(() => {
resolve(`promise-${msg} ${t}s`);
}, t * 1000);
})
}
async function loopAsync() {
console.log('[start]');
const curTime = Date.now();
const tasks = [
['a', 3],
['b', 1],
['c', 2],
];
// 下面写遍历 tasks 传入到异步方法的实现
// 并行写法
const taskPromises = tasks.map(task => {
const [ msg, t ] = task;
return sleepPromise(msg, t).then(m => {
console.log(m);
});
});
await Promise.all(taskPromises);
console.log(`[end] duration ${((Date.now() - curTime) / 1000).toFixed(2)}s`);
}
loopAsync()
console