R
R
romiv2018-05-17 18:30:01
JavaScript
romiv, 2018-05-17 18:30:01

How justified is it to use generators in js?

That is, in this way we are no longer working asynchronously.
And we lose the benefits of asynchrony. The question is mainly about generators in the node for queries to the database.
Maybe I misunderstood something

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2018-05-17
@bingo347

Firstly, generators are not about asynchrony (although you can use it for it, but you don’t need to), generators are about interrupted calculations and managed iterators.
For example, with the help of generators, problems for infinite sequences are well solved:

function* fibo() {
  let prev = 1;
  let prePrev = 1;
  yield prePrev;
  yield prev;
  while(true) {
    let cur = prePrev + prev;
    yield cur;
    prePrev = prev;
    prev = cur;
  }
}

for(let val of fibo()) {
  alert(val);
  if(val > 100) { break; }
}

Secondly, for asynchrony, there are promises and sugar over them in the form of async / await
async function, the same is interrupted when it sees await, like a generator (this is why async / await is emitted on generators when transpiling to the old standard)
but unlike a generator , which waits for the .next() command from external code to continue execution after yeild, the async function waits for the resolve or reject of the promise passed to await

F
forspamonly2, 2018-05-17
@forspamonly2

es2018 has asynchronous generators. babe knows how to do them. in a fresh node, firefox and chrome are already supported natively.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question