3 ms·
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.
- easybake 4y ago> My mild guess is when resolve is called .then part happens, and when reject is called .catch part happens. 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 a 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)`): const handlePromise = function(resolve, reject) { let x = 20; let y = 20; // return "Promises will not 'return' a value, they must be resolved or rejected"; if (x == y) resolve(true); // reject(false) reject(new Error("x != y")) } const handleSuccess = function(value) { console.log(value); } const handleCatch = function(err) { console.log(err); } const example = new Promise(handlePromise); example .then(handleSuccess) .catch(handleCatch); > I feel so dumb for asynchronous javascript. You are in good company. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...