Anyone who learns Android knows that Java is multi-threaded, and when it takes a time-consuming operation, such as requesting data from the server, it is often necessary to open a thread to execute it.
But in our JS, is single-threaded, request network data, we can not determine when will return, if the network is not very good, then it will be very slow. So it is impossible to wait for his request to complete before going to the next steps. So we need to ask for the data asynchronously, but we need to know the result of the request, and then we need an interface callback to tell us the result of the request.
In ES6, promise is provided for asynchronous operations and callbacks are implemented.
Use the following:
var promise = new Promise (function (resolve, reject) {
//perform some asynchronous or time-consuming operations
if (1) {
//condition is met, asynchronous operation succeeds
resolve (" Success! ");
} else {
//condition does not satisfy
reject ("fail");
}
});
The binding handler
Promise.then (function (result) {
//promise succeeded callback
console.log (result);//"Success"
}, function (err) {
//promise failed callback
Console.log (ERR);//Error: "Fail"
});
The
is implemented in three steps:
1. The first step: Create a Promise object and do something in it, such as AJAX request Data
2. Step two: In this object method, specify the condition accordingly. For example, when the AJAX request returns the data state==200, use Resolve ("success!"); Callback, if not, use Reject (Error ("fail"));
3. Step three: Use Promise.then to listen to these two callback functions and make the corresponding actions we expect to succeed or fail.