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?
!await new Promise(resolve => ....is false ... at which point, done === false, which is whatfnwill return!await new Promise(resolve => ....is evaluated tofalseatwhileexpression whentrueis returned whenvalue:undefined, done:true, as evidenced byvalue: truelogged atconsole, though the assigned value is not retained.do..whileloop returns expected result. The question is why is thetruereturned from.then()at last iteration usingawaitassignment is not retained followingwhileloop?fn().then(res =>with the questionwhy is res false... the reason is, thatfn()will always ever only ever return a Promise that resolves to false, ever, never anything else, don't even need to read the 259 characters after the ! ...while done = !.... all this is irrelevant ....);means that the only exit is whendone === false, which is what the function returns after the loop