我开发了一个类,该类几乎没有用于运行和更新数据库内部数据的功能。 我想一次运行我的类的10个线程,并在其中每个线程完成时开始新的运行(因此总是运行10个或更少的操作) 我该怎么办?
代码示例:
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
谢谢!
答案 0 :(得分:1)
您可以在承诺解决后让函数自行调用
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()
})
答案 1 :(得分:0)
如果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);
...