Promise
new Promise
Promiseis a class, so create aPromiseobject using thenewkeywordPromisetakes a callback function that performs asynchronous processing as an argument, and this callback function receivesresolveandrejectfunctions as argumentsWhen a
Promiseobject is created, the callback function is automatically executedIf the code is processed well, call the
resolvefunction, and if an error occurs, call therejectfunctionlet promise = new Promise((resove, reject) => { // 1. When processed normally, pass value to resolve's argument resolve(value); // 2. When error occurs, pass error message to reject's argument reject(value); });
Promise Object's Internal Properties
The Promise object returned by
new Promisehasstateandresultinternal propertiesHowever, cannot access directly and must use
.then,.catch,.finallymethods to accessState
Default state is
pending. If the callback function performing asynchronous processing works well β changes tofulfilled, if error occurs βrejected
Result
Default state is
undefined. If the callback function performing asynchronous processing works well andresolve(value)is called β changes to value, if error occurs andreject(error)is called β changes toerror
then, catch, finally
then
If the code written in the callback function is processed well, call the
resolvefunction β can access through.thenmethodIf the value returned in
.thenis aPromise, receive thePromise's internal propertyresultas the argument of the next.then's callback functionIf it's not a
Promise, can receive the returned value as the argument of.then's callback function
Catch
When an error occurs in the code written in the callback function, call the
rejectfunction and can access through.catchmethod
Finally
Can access through
.finallymethod regardless of whether the code written in the callback function is processed normally
Promise Chaining
When asynchronous tasks need to be performed sequentially
Promise all()
Used when you want to process multiple asynchronous tasks simultaneously
Takes an array as an argument, and if all the code written in the callback functions of all
Promisein that array is processed normally, stores the results in an array and returns a newPromiseAdditionally, if any of the
Promisein the argument array encounters an error, immediately terminates regardless of the state of the remainingPromise
Last updated