Reputation: 665
I read the other day about a special type of callback that progresses with you as you call it repeatedly. As in it does A the first time it's called and returns, then it does B the next time it's called. Eventually it signals in some way that the final action has been taken.
I can't remember what it was called and I can't find it in my history so I don't know what to search. I need help.
Upvotes: 0
Views: 173
Reputation: 111258
You may be talking about generators:
> function* x() { yield 1; yield 2; yield 3; return 4; }
undefined
> var g = x();
undefined
> g.next();
{ value: 1, done: false }
> g.next();
{ value: 2, done: false }
> g.next();
{ value: 3, done: false }
> g.next();
{ value: 4, done: true }
> g.next();
{ value: undefined, done: true }
See:
Generators can be used for asynchronous operations when a generator yields promises instead of values that it wants to return that it itself expects to get injected as a resolved values of those promises in the return value of the yield
statement by the wrapper like that from co
or Bluebird.coroutine
- see:
This was the basis of the new async
and await
keywords in newer versions of JavaScript:
Upvotes: 1
Reputation: 7605
I think what you might be looking for is generator functions
. It has been introduced by ES6.
Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator
See MDN documentation.
Example:
function* idMaker() {
var index = 0;
while (index < 3)
yield index++;
}
var gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // undefined
Upvotes: 1