This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging
preface
In the development of front-end projects, we often apply asynchronous operations, such as Ajax network requests to deal with back-end data business requirements, but often products do not let us worry, business requirements are always asynchronous and synchronous intersection, slowly we will find that many layers of callback to deal with the business turned into a callback hell. This makes our code less readable and more complex, and I recommend using promises here.
Promise to introduce
Promise is a constructor that is a solution to asynchronous programming. The Promse itself is a container that holds the result of an asynchronous operation. Yes, it is similar to a callback function.
The Promise container itself is not asynchronous, but encapsulates an asynchronous task. He has three states, which are unaffected by the outside world, namely:
- Pending (in progress)
- Resolved (successful)
- Rejected (failure)
Basic use of Promise
const promise = new Promise((resolve, reject) = > {
// Do asynchronous tasks (such as Ajax request interfaces). Use timer for the time being)
setTimeout(function () {
var data = {
retCode: 0.msg: 'qianguyihao'
}; // The data returned by the interface
if (data.retCode == 0) { // When the interface request succeeds
resolve(data);
} else { // Called when the interface request fails
reject({
retCode: -1.msg: 'network error'}); }},100);
})
// Accept the arguments passed by resolve or reject after asynchrony ends
promise.then((data) = >{
console.log('success'+data)
},(err) = >{
console.log('failure'+err)
})
Copy the code
Promise() : The Promise constructor is primarily used to wrap functions that do not support Promises (return values that are not Promises). \
The resolve function changes the status of the Promise object from pending to Successful (that is, from Pending to Resolved). The resolve function is called when the asynchronous operation succeeds and the result of the asynchronous operation is passed as a parameter. \
Reject: Reject a Promise object that changes its state from “unfinished” to “Rejected” (from “pending” to “Rejected”). A Promise object is called when an asynchronous operation fails, passing an error as an argument. \
Then: The THEN () method returns a Promise. It takes up to two arguments: the Promise’s success and failure case callbacks.
promise.catch((err) = >{
console.log('failure'+err)
})
Copy the code
// Throw an error, which most of the time will call the catch method
var p1 = new Promise(function(resolve, reject) {
throw 'Uh-oh! ';
});
p1.catch(function(e) {
console.log(e); // "Uh-oh!"
});
// An error thrown in an asynchronous function is not caught by a catch
var p2 = new Promise(function(resolve, reject) {
setTimeout(function() {
throw 'Uncaught Exception! ';
}, 1000);
});
p2.catch(function(e) {
console.log(e); // Will not be executed
});
// Errors thrown after resolve() will be ignored
var p3 = new Promise(function(resolve, reject) {
resolve();
throw 'Silenced Exception! ';
});
p3.catch(function(e) {
console.log(e); // Will not be executed
});
Copy the code
Catch: The catch() method returns a Promise, the callback function that handles the failure, and the error that was thrown (errors thrown in asynchronous functions are not caught by the catch).
conclusion
We can solve the callback hell problem by using the Promise() constructor, promise.resolve (), promise.reject (), promise.then (), promise.catch ().