简体   繁体   English

Node.js:如何防止下一行执行,直到我的 forLoop 给我结果

[英]Node.js: How to prevent the next line execution until my forLoop gives me result

let a = []
    for (let i=0;i<4;i++){
        setTimeout(()=>{
            a.push(i);
        },2000)
    }


console.log(a);

Here I am getting a always blank [].在这里,我得到一个始终空白的 []。 Please suggest a way to stop executing console.log(a) line until a gets filled.请提出一种方法来停止执行 console.log(a) 行,直到 a 被填满。

You should await setTimeout :你应该等待setTimeout

let a = [];
async function test() {
  for (let i = 0; i < 4; i++) {
    await new Promise((resolve) =>
      setTimeout(() => {
        a.push(i);
        resolve();
      }, 2000)
    );
  }
}

await test();

console.log(a);

Note: You can also use Promise.allSettled to run them at the same time注意:也可以使用Promise.allSettled来同时运行它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的 node.js 给了我错误,我不明白是什么问题 - My node.js gives me error and I dont understand what's the problem 当我用 node.js 运行我的程序时,有没有办法让它 windows 给我一个弹出窗口? - Is there a way to make it so windows gives me a popup when I run my program with node.js? 如何等到 request.get 完成然后在 node.js 中执行下一个块 - How to wait until request.get finish then conduct the next block in node.js 如何转换node.js的结果以防止ember.js错误:找不到“ 0”的模型? - How I can transform the result of node.js to prevent ember.js error: No model was found for '0 '? 如何在Node.js中停止异步执行 - How to stop async execution in node.js 如何防止node.js中的竞争状况? - How to prevent race condition in node.js? next()在Node.js中如何工作? - How does next() work in Node.js? 如何在angular js 1.6中使用async:false,以便Java脚本下一行执行得到阻塞,直到$ http完成 - How to use async:false in angular js 1.6, so that java script next line execution get block until $http completed 如何在 node.js 中的某个前一行之后捕获下一个 tine - How to capture next tine after the certain previous line in the node.js 如何将此 Node.js 结果下载到浏览器? - How to Download This Node.js Result to Browser?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM