我创建了两个 JS 函数。第一个使用 For 循环,第二个在 1 秒延迟后打印文本。然后我就这样称呼他们。
// Code block 1
console.log("Function Begins");
functionWithLoop().then(function (result) {
console.log("Function Ends");
});
// Code block 2
function functionWithLoop() {
return new Promise(function(resolve, reject)
{
for (let loopcount = 1; loopcount <= 3; loopcount++) {
MyCustomPrintFunction(loopcount).then(function(resolve)
{
console.log("After custom print function : index " + loopcount);
});
}
resolve();
});
}
// Code block 3
function MyCustomPrintFunction(text) {
return new Promise(function(resolve, reject)
{
setTimeout(() => {
console.log("In custom print function " + text);
resolve();
}, 1000);
});
}
期望的是,控制台日志顺序将是这样的:
Function Begins
In custom print function 1
After custom print function : index 1
In custom print function 2
After custom print function : index 2
In custom print function 3
After custom print function : index 3
Function Ends
但是控制台按以下顺序打印:
Function Begins
Function Ends
In custom print function 1
After custom print function : index 1
In custom print function 2
After custom print function : index 2
In custom print function 3
After custom print function : index 3
为什么第一个
then()
语句不等待整个循环完成?我在这里做错了什么?
在 for 循环中,您正在创建独立于周围 Promise 运行的新 Promise,请使用
async
和 await
按顺序运行它们:
// Code block 1
console.log("Function Begins");
functionWithLoop().then(function (result) {
console.log("Function Ends");
});
// Code block 2
function functionWithLoop() {
return new Promise(async function(resolve, reject)
{
for (let loopcount = 1; loopcount <= 3; loopcount++) {
await MyCustomPrintFunction(loopcount)
console.log("After custom print function : index " + loopcount);
}
resolve();
});
}
// Code block 3
function MyCustomPrintFunction(text) {
return new Promise(function(resolve, reject)
{
setTimeout(() => {
console.log("In custom print function " + text);
resolve();
}, 1000);
});
}