Node.js:for循环后执行
Node.js: Execution after for loop
我正在构建一些 Node.js 应用程序并具有如下功能:
function ex() {
allowUA = false;
for (var i = 0; i < arr.length; i++) {
(function(index) {
setTimeout(() => {
console.log(index);
}, i * 3000);
})(i);
}
if (i == arr.length - 1) {
allowUA = true;
}
}
我想要的只是按严格顺序执行的函数(将变量更改为 false,执行循环,然后将变量更改回 true)
我发现这并不像看起来那么容易,所以我请求你的帮助。
有办法吗?提前致谢。
您可以使用 Promise
来确保超时首先解决,然后在所有承诺解决时记录下一个条件。
let allowUA = false;
let arr = [1, 2, 3]
function ex() {
allowUA = false;
console.log('false');
// iterate over the array and create a promise for each iteration
let promises = arr.map(function(value, index) {
return new Promise(function(resolve) {
setTimeout(() => {
console.log(index);
// resolve the promise
resolve();
}, index * 500);
});
})
// run this when all the promises resolve themselves
Promise.all(promises).then(function() {
allowUA = true;
console.log('true');
});
}
ex()
这是一个 async/await
方法,该方法放弃了 for/loop,转而使用 setTimeout
,它调用具有缓慢缩短数组的函数:
async function ex(arr) {
allowUA = false;
console.log(allowUA);
function logger(arr) {
return new Promise((resolve, reject) => {
(function loop(arr) {
const [head, ...rest] = arr;
if (!arr.length) {
resolve();
} else {
console.log(head);
setTimeout(() => loop(rest), head * 1000);
}
}(arr));
});
};
await logger(arr);
allowUA = true;
console.log(allowUA);
}
const arr = [1, 2, 3, 4];
ex(arr);
我正在构建一些 Node.js 应用程序并具有如下功能:
function ex() {
allowUA = false;
for (var i = 0; i < arr.length; i++) {
(function(index) {
setTimeout(() => {
console.log(index);
}, i * 3000);
})(i);
}
if (i == arr.length - 1) {
allowUA = true;
}
}
我想要的只是按严格顺序执行的函数(将变量更改为 false,执行循环,然后将变量更改回 true)
我发现这并不像看起来那么容易,所以我请求你的帮助。
有办法吗?提前致谢。
您可以使用 Promise
来确保超时首先解决,然后在所有承诺解决时记录下一个条件。
let allowUA = false;
let arr = [1, 2, 3]
function ex() {
allowUA = false;
console.log('false');
// iterate over the array and create a promise for each iteration
let promises = arr.map(function(value, index) {
return new Promise(function(resolve) {
setTimeout(() => {
console.log(index);
// resolve the promise
resolve();
}, index * 500);
});
})
// run this when all the promises resolve themselves
Promise.all(promises).then(function() {
allowUA = true;
console.log('true');
});
}
ex()
这是一个 async/await
方法,该方法放弃了 for/loop,转而使用 setTimeout
,它调用具有缓慢缩短数组的函数:
async function ex(arr) {
allowUA = false;
console.log(allowUA);
function logger(arr) {
return new Promise((resolve, reject) => {
(function loop(arr) {
const [head, ...rest] = arr;
if (!arr.length) {
resolve();
} else {
console.log(head);
setTimeout(() => loop(rest), head * 1000);
}
}(arr));
});
};
await logger(arr);
allowUA = true;
console.log(allowUA);
}
const arr = [1, 2, 3, 4];
ex(arr);