我需要同步运行startFunc函数,并在for循环中“等待”完成任务,然后再次运行它。我不能在startFunc()中使用await。 我需要类似C#中的.wait()之类的东西 我除了结果: 开始1 结束1 开始2 结束2等...
function callToDB(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function startFunc (i) {
console.log('start', i);
await callToDB(1000);
console.log('end', i);
}
for (let i = 0; i < 5; i++) {
startFunc(i);
}
答案 0 :(得分:2)
您还需要将for
循环放入async
函数中,以便可以await
每次调用startFunc
:
function callToDB(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function startFunc (i) {
console.log('start', i);
await callToDB(1000);
console.log('end', i);
}
(async () => {
for (let i = 0; i < 5; i++) {
await startFunc(i);
}
})();
.then
:
function callToDB(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function startFunc (i) {
console.log('start', i);
await callToDB(1000);
console.log('end', i);
}
let prom = Promise.resolve();
for (let i = 0; i < 5; i++) {
prom = prom.then(() => startFunc(i));
}
或者您可以使用.reduce
并持续传递最后一个Promise作为累加器,而不是分配给外部变量:
function callToDB(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function startFunc (i) {
console.log('start', i);
await callToDB(1000);
console.log('end', i);
}
const finalProm = Array.from({ length: 5 })
.reduce(
(lastProm, _, i) => lastProm.then(() => startFunc(i)),
Promise.resolve()
);