Javascript 如何在节点中提示和等待setImmediate?
我一直在读关于如何不阻止节点的事件循环的书。避免阻塞的一种方法是使用 我试图在代码中使用分区循环,但我似乎不能等待我的循环。以下是我的代码的简化版本:Javascript 如何在节点中提示和等待setImmediate?,javascript,node.js,recursion,async-await,setimmediate,Javascript,Node.js,Recursion,Async Await,Setimmediate,我一直在读关于如何不阻止节点的事件循环的书。避免阻塞的一种方法是使用 我试图在代码中使用分区循环,但我似乎不能等待我的循环。以下是我的代码的简化版本: const report = { someValue: 0 }; const runLoop = async () => { report.someValue += 1; // all sorts of async operations here that use
const report = {
someValue: 0
};
const runLoop = async () => {
report.someValue += 1;
// all sorts of async operations here that use async-await
if (report.someValue < 1000) {
await setImmediate(runLoop);
}
};
await runLoop();
console.log('Report is', report);
const报告={
someValue:0
};
const runLoop=async()=>{
report.someValue+=1;
//这里所有使用异步等待的异步操作
如果(report.someValue<1000){
等待setImmediate(runLoop);
}
};
等待runLoop();
console.log('Report is',Report);
这将返回“Report is{someValue:1}”,但我希望someValue为1000
我猜setImmediate不会回报承诺,所以我试着承诺:
const setImmediatePromise = util.promisify(setImmediate);
const report = {
someValue: 0
};
const runLoop = async () => {
report.someValue += 1;
// all sorts of async operations here that use async-await
if (report.someValue < 1000) {
await setImmediatePromise(runLoop);
}
};
await runLoop();
console.log('Report is', report);
const setImmediatePromise=util.promisify(setImmediate);
常数报告={
someValue:0
};
const runLoop=async()=>{
report.someValue+=1;
//这里所有使用异步等待的异步操作
如果(report.someValue<1000){
等待setImmediatePromise(运行循环);
}
};
等待runLoop();
console.log('Report is',Report);
但这也会返回“Report is{someValue:1}”
那么,我如何才能等待这个递归setImmediate“循环”,以便仅在整个递归周期结束后才返回console.log报告呢?当您承诺
setImmediate
时,您不再向它传递回调。相反,您只需等待它返回的承诺。然后,您将执行递归调用:
async function runLoop() {
…
if (…) {
await setImmediatePromise();
return runLoop();
}
}
但是,async
/await
提供了只编写实际循环的功能:
const setImmediatePromise = util.promisify(setImmediate);
const report = {
someValue: 0
};
while (report.someValue < 1000) {
report.someValue += 1;
// all sorts of synchronous operations here
await setImmediatePromise();
}
console.log('Report is', report);
const setImmediatePromise=util.promisify(setImmediate);
常数报告={
someValue:0
};
而(report.someValue<1000){
report.someValue+=1;
//这里有各种各样的同步操作
等待setImmediatePromise();
}
console.log('Report is',Report);
(注意递归的细微差别:在第一次迭代之前已经检查了条件,并且在最后一次迭代之后,setImmediate
再次运行。如果需要,使用do
/while
或者甚至while(true)
+if(…)break;
。)
顺便说一句,如果您已经在循环内执行异步(非阻塞)操作,则没有理由向其添加额外的
setImmediate
。只处理会阻塞事件循环的复杂同步计算。这似乎可行,谢谢!我是否理解正确:在您的示例中,await setImmediatePromise()代码>在while循环中,使while循环不阻塞?@iepure是的。一定要明白。尝试用newpromise
而不是util.promisify
(仅用于实践)编写相同的内容。