【问题标题】:How would I do a for loop that waits until my function has completed for each loop?我将如何做一个等待直到我的函数完成每个循环的 for 循环?
【发布时间】:2020-02-27 04:24:08
【问题描述】:

我当前的代码是这样的:

const fs = require('fs');
var file = fs.readFileSync('file.txt').toString().split("\n");

for(i in file) {
    var [thing1, thing2, thing3] = file[i].split(":");
    myfunction(thing1, thing2, thing3);
}

这会为文件中的每一行执行一个函数,其中包含文件中的一些信息。由于技术原因,我一次只能让该功能运行一次。 如何让 for 循环在再次循环之前等待函数完成?

【问题讨论】:

  • 函数一次运行一个,除非它们是异步的。 myfunction() 是什么?它有什么作用?是异步函数吗?
  • 假设 myfunction() 是同步的(不返回 Promise 并且未标记为 async)它已经等待。否则,你可以使用async/await 做你想做的事。

标签: javascript node.js for-loop


【解决方案1】:

如果 myfunction 是同步一,则您的代码已经在工作

否则:

await myfunction(thing1, thing2, thing3);

确保将 async 添加到代码块中:

(async () => {
  for(i in file) {
     var [thing1, thing2, thing3] = file[i].split(":");
     await myfunction(thing1, thing2, thing3);
}})();

【讨论】:

  • 我补充说,但现在我的控制台什么也没返回。 (我假设因为该函数从未运行过)
  • 您应该补充一点,以便从await 中获得任何好处,myfunction() 必须返回一个与完成异步操作时相关联的承诺。如果它没有返回这样的承诺,那么await 是无用的,不会做任何事情。
  • (对不起,如果这是一个愚蠢的问题,我是 js 新手)我怎么知道这个函数会返回一个承诺?
【解决方案2】:

我的方法是让myfunction await-able 像这样:

async function myfunction (thing1, thing2, thing3) {
    // perform your operations here
    return 'done'; // return your results like object or string or whatever
}

这样for循环就可以在每次迭代时等待它的完成,像这样:

const fs = require('fs');
const file = fs.readFileSync('file.txt').toString().split("\n");

// This main function is just a wrapper to initialize code
async function main() {
    for(i in file) {
        let [thing1, thing2, thing3] = file[i].split(":");
        let result = await myfunction(thing1, thing2, thing3);
            console.log(`Result of ${i} returned`);
    }
}

main();

如需完整运行示例,请克隆 node-cheat 并运行 node loop-await.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2014-08-15
    • 2022-01-09
    • 2014-07-19
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多