Promise
Promise States:
Pending - Operation is still running
Fulfilled - Operation has finished successfully
Rejected - Operation has failed (normally an error)
const executorFunction = (resolve, reject) => {
if (someCondition) {
resolve('I resolved!');
} else {
reject('I rejected!');
}
};
const promiseName = new Promise(executorFunction);What is the resole and reject functions?
resolveis a function with one argument. Under the hood, if invoked,resolve()will change the promise’s status frompendingtofulfilled, and the promise’s resolved value will be set to the argument passed intoresolve().
rejectis a function that takes a reason or error as an argument. Under the hood, if invoked,reject()will change the promise’s status frompendingtorejected, and the promise’s rejection reason will be set to the argument passed intoreject().
.then - Promise handlers
Method 1
const prom = new Promise((resolve, reject) => {
if (condition) {
resolve('went well');
} else {
reject('went bad');
}
});
// what happens after a resolve... resolvedValue will = 'went well'
const handleSuccess = (resolvedValue) => {
console.log(resolvedValue);
};
// what happends after a reject... rejectionReason will = 'went bad'
const handleFailure = (rejectionReason) => {
console.log(rejectionReason);
};
prom.then(handleSuccess, handleFailure);Method 2
// Note, this works because, the first then will,
// return the setteled value from the resolved,
// thus we can then run the second then/catch for the rejection
prom(order)
.then(handleSuccess)
.catch(handleFailure);Chaining Promises (DONT NEST THEM)
firstPromiseFunction()
.then((firstResolveVal) => {
return secondPromiseFunction(firstResolveVal);
})
.then((secondResolveVal) => {
return thirdPromiseFunction(secondResolveVal);
})
.catch((error) => {
// ... do whatever with the error message
});Concurrent Promises ALL
let myPromises = Promise.all([returnsPromOne(), returnsPromTwo(), returnsPromThree()]);
myPromises
.then((arrayOfValues) => {
console.log(arrayOfValues);
})
.catch((rejectionReason) => {
console.log(rejectionReason);
});setTimeout
Will delay the execution of a function... after n time, the function will be added to the execution stack (I presume)
Note: rest of the program still executes
setTimeout(funcName, 2000); // 2 sec timeout