Given the JavaScript code
function* gen(start = 0, stop = 5) {
while (start < stop) yield ++start;
}
async function fn(g = gen()) {
while (done = !await new Promise(resolve =>
setTimeout(resolve, 1000, g.next()))
.then(({value, done}) => {
// `value:undefined, done:true` following
// `value:5, done:false`
console.log(`value:${value}, done:${done}`);
return done
}
, err => Promise.reject(err)));
return done; // what happened to the `true` value assigned?
}
// why is `res` `false`?
fn().then(res => console.log(`res:${res}`), err => console.error(err));
the expected result of done
returned from fn()
is true
when done
is assigned the value true
that is returned from .then()
within while
expression.
Why is the assignment using await
at while
statement expression not retained?