我将如何执行for循环,直到每个循环的功能完成?

问题描述 投票:0回答:2

我当前的代码是这样:

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循环在再次循环之前等待函数完成?

javascript node.js for-loop
2个回答
1
投票

如果我的功能已同步,则您的代码已在工作中

其他方式:

await myfunction(thing1, thing2, thing3);

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

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

0
投票

我的方法是使myfunction await像这样:

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();
© www.soinside.com 2019 - 2024. All rights reserved.