Answer the question
In order to leave comments, you need to log in
Asynchronous JavaScript Loop & Generators?
Hey!
I use the AdonisJS framework, whose controller methods act as generator functions.
There is a code:
* tasks() {
let tasks = yield Task.findBy('status', 1)
for(let task of tasks) {
yield this.task(task)
}
}
Answer the question
In order to leave comments, you need to log in
If the framework under the generators is based on promises, that is, there is an imitation of async / await, then this should help:
* tasks() {
let tasks = yield Task.findBy('status', 1)
let promises = []
for(let task of tasks) {
promises.push(this.task(task))
}
yield Promise.all(promises)
}
javascript is a single-thread language. you will not call this.task(task) in parallel for all array elements. asynchronous does not mean that the code is executed in parallel, it is just executed in a non-blocking style. even promise.all() is not executed in parallel. to execute the code in parallel - you need to execute it in a separate thread (webworkers).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question