Introduction and Basic Usage of Promise
- 2021-11-29 22:54:01
- OfStack
Promise is a new asynchronous programming solution introduced by ES 6. Syntax Promise is-1 constructor,
Used to encapsulate asynchronous operations and get their success or failure results.
Basic Use of Promise
Instantiate Promise
new Promise()
Accept 1 parameter when instantiating, and this parameter is 1 function.
This function has two formal parameters, resolve and reject
var promise = new Promise((resolve,reject) => {
// It is used to handle asynchronous operations
})
We use timers here to simulate asynchronous operations
promise has three states, which are in progress, successful and failed.
var promise = new Promise((resolve,reject) => {
// This is 1 Asynchronous operations
setTimeout(() => {
// Here, the simulation acquires data
var data = ' Acquired data '
// After we get the data, we can call resolve And reject Method to change promise The state of the object
resolve(data) // resolve You can set the promise Object is changed to Success, reject() Yes promise Change object status to failure
}, 1000);
})
then method of promise
You can call the then method when the status of the promise object is success or failure
The then method takes two arguments, and both arguments are values of the function type
When the status of the promise object is Success, the first parameter of the then method is called
This means that the second parameter of the then method is called when the state of the promise object is failed
The second parameter is optional and can be omitted if the capture failure is not required
Parameters have one formal parameter, the successful function is called value, and the failed err
promise.then(value => {
// When an asynchronous function calls resolve(data) , that is, just say promise Object is called when the status of the then The first of the method 1 Parameters
console.log(value); // 'hello world' value Is resolve() The data passed by the method
}, err => {
// When an asynchronous function calls reject(data) , that is, just say promise Object is called when the status of the then The first of the method 2 Parameters
console.log(err); // err Is reject() The data passed by the method
})
The return result of calling then method then method is Promise object, and the state of object is determined by the execution result of callback function
If the result returned in the callback function is a non-promise type attribute, the status is successful and the return value is the successful value of the object
let data = promise.then((val) => {
// console.log(val.result);
// Returns non Promise The situation of
// return val.result
// Return Promise The situation of
return new Promise( (resolve, reject) => {
// resolve('ok')
reject('err')
})
}, err => {
console.log(err);
})
// Returns non Promise The situation of The status is successful, and the return value is the successful value of the object
// The result returned is Promise Object whose state is determined by the execution result of the callback function
// Throw an error , The status is Failure
console.log(data);
Therefore, then can be called in a chain. See the following promise application example.
catch Method of promise
The catch method of promise is an alias for then (null, rejection) that specifies the callback when an error occurs
If the Promise object has a state of resolve, the specified callback function of the then method is called
const promise = new Promise((resolve, reject) => {
resolve('ok')
})
promise.then(val => {
console.log(val); // ok
}).catch(err => {
console.log(err);
})
If the state of promise is rejected, the callback function of the catch method is called to handle this problem.
const promise = new Promise((resolve, reject) => {
reject('err')
})
promise.then(val => {
console.log(val);
}).catch(err => {
console.log(err); // err
})
If the then method has an error in operation, it will also be caught by the catch method
const promise = new Promise((resolve, reject) => {
resolve('err')
})
promise.then(val => {
console.log('ok'); // ok
throw ' There's been a mistake! ! ' // then The errors thrown in it will continue to be catch Capture
}).catch(err => {
console.log(err); // There's been a mistake! !
})
Errors in the promise object have a bubbling nature and are passed straight back until they are caught. That is, errors are always caught by the next catch.
const promise = new Promise((resolve, reject) => {
resolve('ok')
})
promise.then(val => {
return new Promise((resolve, reject) => {
reject('err')
})
})
.then(val => {
return new Promise((resolve, reject) => {
reject('err')
})
})
.catch(err => {
// All the above errors can be catch Capture to
console.log(err); // err
})
1 In general, do not define the rejected state callback function (that is, the second parameter of then) in the then method, but always use the catch method.
promise application
promise reads files, and multiple files are called continuously
In this example, we use the file module of Node. js
// Read file information
const fs = require('fs')
In the following code, we use promise to wrap asynchronous functions
Let's look at the normal file read operation first
var promise = new Promise((resolve,reject) => {
// It is used to handle asynchronous operations
})
0
If we want to continue reading the file after reading successfully, we need to continue to use fs. readFile... in the callback function to read the file, nesting more than 1 level, so 1 will form a callback hell.
Next, we use Promise to read the file
var promise = new Promise((resolve,reject) => {
// It is used to handle asynchronous operations
})
1
promise encapsulates ajax requests
Encapsulated the ajax request, using then to get results, let the code look more concise, and solve the problem of callback hell
var promise = new Promise((resolve,reject) => {
// It is used to handle asynchronous operations
})
2