简体   繁体   English

如何等待多个异步函数完成?

[英]How to wait to multiple async function to finish?

I've devloped a class that has few function that run and update data inside of a database.我开发了一个类,它几乎没有运行和更新数据库内数据的功能。 I want to run 10 threads of my class at a time , and start new run everytime one of them is done (so there always be 10 operations running or less) How can I accomplish it?我想一次运行我班级的 10 个线程,并在每次完成其中一个线程时开始新的运行(所以总是有 10 个或更少的操作在运行)我怎样才能完成它?

Example of the code:代码示例:

const classobj = require("data.js");
    let class1 = new Data();
    let class2 = new Data();
    ... //(8 more)

    class1.run();
    class2.run();
    ... // (8 more)

    // one one of the class1-10 is done i want it to start again

Thank you!谢谢!

You can make the function call itself when the promise resolves您可以在承诺解决时使函数自行调用

 const randomDelay = () => (Math.floor(Math.random() * 5) + 2) * 1000 const fakePromise = id => new Promise(res => setTimeout(() => { console.log(`class ${id} finished work`) res() }, randomDelay())) class MyClass { constructor(id) { this.id = id } run = () => { console.log(`class ${this.id} starting work`) fakePromise(this.id).then(this.run) } } // create 3 instances and call .run() on every one [...new Array(3)] .map((_, i) => new MyClass(i + 1)) .forEach(classInstance => { classInstance.run() })

If the Data.run function returns a Promise, you could do something like this:如果Data.run函数返回一个 Promise,你可以这样做:

const classobj = require("data.js");

const restartingPromise = (promise) => {
  promise().then(() => {
    restartingPromise();
  });
};

let class1 = new Data();
let class2 = new Data();
... //(8 more)

restartingPromise(class1.run);
restartingPromise(class2.run);
...

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM