How do promises program flow work in JavaScript?
Promises syntax that I learnt:
let p = new Promise(function (resolve, reject) {
let x = 20, y = 20;
if (x == y) {
resolve();
}
else {
reject();
}
})
p.then(function () {
console.log("that's correct");
})
.catch(function () {
console.log("that's not correct");
})
I don't even understand what happens here, the flow control of here. My mild guess is when resolve is called .then part happens, and when reject is called .catch part happens.I've like read countless articles, banged my head against the wall but it's still not getting inside my head. I feel so dumb for asynchronous javascript.
Please help me understand the program flow step by step in more detail.
Yes, calling `resolve` or `reject` will "fulfill" the Promise (that is, the control-flow then returns to the context in which the Promise was invoked.)
Your example is missing an important detail which makes Promises useful. Both `resolve` and `reject` accept an argument which is passed to the callback function (`example.then(handleSuccess)` and `example.catch(handleCatch)`):
> I've like read countless articles, banged my head against the wall but it's still not getting inside my head. I feel so dumb for asynchronous javascript.Context is everything... Promises can be used to `await` asynchronous operations or run synchronous operations in the background. Another use-case is to gracefully handle failed `Fetch` requests (providing notification to the user that a background operation has failed, while also squelching the exception which is thrown during request timeouts, etc...)
> I feel so dumb for asynchronous javascript.
You are in good company.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
[edit: formatting]