Two points of confusion:
- How are function frames preserved and disposed?
Example:
function foo() {
var a = ...;
setTimeout(function() {
console.log(a);
},50);
return a;
}
In this example, the inner function in setTimeout is referencing the outer variable a, even after foo has returned. Coming from the Java world, I am confused as to how this can happen? How does the foo stack frame get stored for the inner function's use, and when does it get popped off the stack?
- Multiple async/promise "returns"
Example:
async function foo2() {
var p = new Promise() {
setTimeout(function() {
p.reject(null);
},60000);
p.resolve(await dbcall.execute());
}
return p;
}
And somewhere else:
foo2.then(resolve, reject) {
...
}
Suppose the timeout call happens first, and then the dbcall returns. The promise will potentially be resolved twice.
Question(s): After the timeout call rejects, will the function still keep (a)waiting for db call to return, and then execute whatever code comes after await? And what happens with a second fulfillment of the promise (ie the resolve call when await has completed) Does only the first resolve/reject get processed?