C
C
carroll2017-04-13 22:11:03
JavaScript
carroll, 2017-04-13 22:11:03

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)
    }
  }

It is necessary to make sure that the contents of the loop do not execute this.task synchronously, but run the loop in parallel. Question - HOW?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2017-04-14
@carroll

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)
  }

I
Islam Ibakaev, 2017-04-13
@devellopah

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 question

Ask a Question

731 491 924 answers to any question