- async/Promise introduces an independent execution that would block otherwise
- "Later" happens at the completion of its blocking thread
- The callback you attach to .then() gets executed at that "later" time
Here is an example that may clear up some of the fog.
- Note the two independent threads after setFree() is called.
- gone() has gone on to do its own thing
- setFree() returns immediately.
- A common variable waitOver is shared between the two executions
- The then() handler "knows" and takes care of things at that "later" time
- That handler updates the common variable waitOver to inform those interested in knowing what happens at that "later" time
"
let waitOver = false;
let whatToDo = setFree("Jill",5);
console.log(whatToDo);
let theWait = setInterval( () => {
waitOver ? clearInterval(theWait) :
console.log(" and .. wait");
}, 1000);
function gone(secs) {
return new Promise(resolve => setTimeout(resolve, secs*1000));
}
function setFree(someone,secs) {
console.log(`If you truly love ${someone}, set ${someone} free`);
gone(secs).then(() => {
console.log(`Back! ${someone} is yours`);
waitOver = true;
return `${someone} is yours`;
}).catch(`Hunting ${someone} down and kill ${someone}`);
return " Here you wait ... ";
}
This is what you'll get:
If you truly love Jill, set Jill free
Here I wait ...
and .. wait
and .. wait
and .. wait
and .. wait
Back! Jill is yours*
NOTICE ALSO that after calling setFree(), any check on waitOver in the main execution thread would be false unless that check is made after gone() has been handled by its .then() handler.
If there is no .then() handler then gone() would have gone to the woods, and you will never know if Jill ever came back, even if she did because that completion was never handled :-)