For promise & co-routine, I've used bluebird npm package in NodeJs.
Can someone please help in understanding the behavior of below code when promise is getting resolved multiple times.
Question:
What will happens to coroutine when the promise resolved for multiple times?
Will the second yield will be affected by the multiple yield of first.
const bluebird = require("bluebird");
function func1() {
return new bluebird((resolve, reject) => {
let c = 0;
let iterval = SetInterval(() => {
c++;
let cc = c;
console.log(`c=${c}`);
if(cc === 20) {
clearInterval(interval);
}
resolve(true);
}, 1000);
});
}
let run1 = bluebird.coroutine(function*() {
try {
yield func1();
yield func1();
yield func1();
yield func1();
} catch (e) {
console.dir(e);
}
});
Nothing. resolve
and reject
are issued as a pair of anonymous functions by the promise constructor. Once one of them has been called, further call to either of them are ignored.
Note new interval timers are called each time func1
is called, without stopping those previously started, so expect the console output to look messy.
Also each call to func1
returns a different, new promise.
No because the postulate is incorrect. The first yield does not yield multiple times, it returns a promise that is resolved after one second. It's in a generator function, which resumes at the line after the previous yield (the last time I checked). The coroutine is about calling the generator function after the promise returned in the previous yield becomes settled. See http://bluebirdjs.com/docs/api/promise.coroutine.html for more details.