Here's the start:
It 's written in front .
Suppose that a daily development encounters a requirement that multiple interfaces asynchronously request, and that the second interface relies on the first
After the interface has been executed, the data can be used for a series of operations. It is usually written like this:
A.fetchdata ({
URL: ' http://... ',
success:function (data) {
A.fetchdata ({
//) to perform the next step after the first request succeeds
URL: ' http://... ',
success:function (data) {
//...}}}}
);
This is no problem, but there are two disadvantages:
1, when there are multiple operations, will result in multiple callback function nesting, not beautiful
2. If there are several operations that do not have a sequential order, such as when the last request above does not depend on the return result of the previous request,
You also need to wait for the previous operation to complete before implementing the next operation.
Starting with ES6, promise objects can solve the above problems. What is a Promise object
A Promise object can be understood as an action to be performed once, and a promise object can be used after a chain call
To organize your code to make it more intuitive. Resolve and Reject
First look at the code:
function HelloWorld (Ready) {return
new Promise (function (resolve, reject) {
if (ready) {
resolve ("Hello Wor Ld! ");
} else {
reject ("good bye!");
}
);
HelloWorld (True). Then (function (message) {
alert (message);
}, Function (Error) {
alert (error);
});
The above code implementation is very simple, the Helloword function accepts an argument, and if true, prints "Hello world!",
If False, the wrong information is printed. The Helloword function returns a Promise object.
There are two important methods in the Promise object ———— resolve and reject.
The Resolve method allows the state of the Promise object to be changed to succeed, passing a parameter for subsequent successful operations.
In this case, Hello world! String.
The Reject method is to change the state of the Promise object to a failure, while passing the wrong information to the subsequent error-handling operation. then
There are three states of the Promise object:
1.Fulfilled can be understood as a state of success
2.Rejected can be understood as the state of failure
3.Pending is neither a fulfilld nor a rejected state, it can be understood as the initial state of the Promise object instance when it was created.
The then method in HelloWorld's example is to determine what action to perform based on the state of the Promise object, and resolve to execute the first
function (onfulfilled), reject executes a second function (onrejected). The promise mode is in one of the following three states at any time: incomplete (unfulfilled), completed (resolved), and reject (rejected). Taking the Commonjs promise/a standard as an example, the then method on the Promise object is responsible for adding processing functions for the completed and rejected states. The then method returns another promise object to facilitate the formation of the promise pipeline, a way of returning promise objects that enables developers to concatenate asynchronous operations, such as then (Resolvedhandler, Rejectedhandler); The Resolvedhandler callback function fires when the Promise object enters the completion state and the result is passed, and the Rejectedhandler function is invoked in the rejected state.
Example code 1:
function Printhello (Ready) {
var promise = new Promise (function (resolve, reject) {
if (ready) {
Resolve ("Hel Lo ");
} else {
reject ("Good Bye");
}
)
; return promise;
}
function Printworld () {
console.log (' World ');
}
function Printexclamation () {
console.log ('!!! ');
}
Printhello (True)
. Then (function (message).
then (Printworld)
. Then (printexclamation)
. catch ( Function (Error) {
console.log (error);
;
The function first executes the Printhello, returns a Promise object, and concatenates the asynchronous operations by then.
The execution result should be Hello
World
!!!
Example code 2:
function HelloWorld (ready) {return new Promise (function (resolve, reject) {if (Ready)
{Resolve ("Hello world!");
else {reject ("good bye!");
}
});
var _this = this; Printhello (True). Then (function (message) {var request_url = ' Https://raw.githubusercontent.com/facebook/react-nativ
E/master/docs/moviesexample.json '; return fetch (Request_url). Then ((response) => Response.json ()). Then ((responsedata) => {var mo
Vie = responsedata.movies[1];
Console.log (' data = ', movie.title);
return movie.title;
})},function (Error) {return (error);
}). Then (function (message) {return message + ' world ';
}). Then (function (message) {return message + '!!! ';
}). Then (function (message) {console.log (message);
Console.log (' finally ');
). catch (function (error) {Console.log (error); });
The above code has two promise, the first promise after execution is Printhello, will execute the next then,
The then returns a promise that gets the data, and the promise that follows then to the Promise object. The above example prints out the corresponding content in order by means of chained call. Then can use a chained call because it always returns a Promise object every time the method is executed. In addition, the return value in the then onfulfilled function can be used as an argument for subsequent operations. Catch
The Catch method is a simple way of writing onrejected functions in the then (onfulfilled, onrejected) method, which means
Can be written as then (FN). catch (FN), equivalent to then (FN). Then (null, FN). The use of catch is more clearly defined than the general wording. Easy Mistakes that beginners use 1. Forget to add catch () method
This is a very common mistake. Many programmers are very confident in the promise call in their code and feel that the code will never throw an error
Or maybe they simply forgot to add the catch () method. Unfortunately, the No catch () method will let the exception thrown in the callback function be swallowed,
In your console is not to see the corresponding error, which is very painful for debugging.
To avoid this bad situation, I've developed the habit of adding the following code at the end of my promise call chain:
Somepromise (). Then (function () {return
apromise ();
}). Then (function () {return
anotherpromise ();
}). catch (function (error) {
console.log (error);
});
Even if you don't intend to handle exceptions in your code, adding catch () in your code is also a cautious programming style. In some cases
This makes your debugging work easier when your original assumptions go wrong. 2.return confusion and Chaos
Within the then method, we can do three things:
1.return a Promise Object
2.return a synchronized value or a undefined.
3. Sync throw an error
After understanding these three kinds of situations, you will understand promise.
1. Return another Promise Object
This type of writing is common in related articles about promise, as described above for a piece of code that forms the promise chain:
Getuserbyname (' Nolan '). Then (function (user) {return
fetch (REQUEST_URL)
. Then ((response) => Response.json ())
. Then ((responsedata) => {
}
}). Then (function () {
});
2. Return a specific value or undefined
Getuserbyname (' Nolan '). Then (fcuntion (user) {
if (inmemorycache[user.id)) {return
inmemorycache[user.id];
Returning a value!
}
return inmemorycache[user.id];
Returning a Promise
}). Then (function (useraccount) {
//I got a user account
})
If the return statement is not invoked, the function in JavaScript returns undefined. And that means that when you want to return some value,
Calling return without an explicit call can have some side effects.
For the above reasons, the habit of a person is to be in the then method always explicit call return or throw. I also recommend that you do so.
3. Throw an error
Speaking of throw, this also embodies the powerful function of promise. When the user exits, our code is handled in a way that throws an exception:
Getuserbyname (' Nolan '). Then (function (user) {
if (user.isloggedout ()) {
throw new Error (' User logged out! ');
Throwing a error!
}
if (Inmemorycache[user.id]) {return
inmemorycache[user.id];
Returning a value!
}
Return Getuseraccountbyid (user.id);
Returning a promise!
}). Then (function (useraccount) {
//I got a user account!
}). catch (function (err) {
//Boo, I got an error!
});
If the user has logged out, catch () will receive an error if the Promise object's status changes to rejected.
It will also receive an error.
Throwing exceptions when using promise is useful in the development phase, and it helps us locate bugs in our code. Say
Calling Json.parse () inside the then function may throw an exception if the JSON object is not legitimate, and the exception will be swallowed in the callback function, but after using promise, we can catch the exception.
Author: Meiqing
Link: http://www.jianshu.com/p/174d9892283f
Source: Jianshu