Dowemo
0 0 0 0

Start:

Write in front

Assuming that a daily development will encounter such a requirement: Multiple interfaces asynchronous requests, the second interface depends on the fi t

A series of operations can be performed after the interface is completed. It's usually written in this way:

 A.fetchData({
 url: 'http://......',
 success: function (data) {
 A.fetchData({
//要在第一个请求成功后才可以执行下一步
 url: 'http://......',
 success: function (data) {
//......
 }
 });
 }
 });

There's no problem writing, but there are two disadvantages:


1, when more than one operation occurs, multiple callback functions are nested, not beautiful


2, if there are several operations that aren't in order, such as the latter one, the latter request doesn't depend on the return result of the previous request

Also need to wait for the previous operation to complete the next operation.


From es6, the promise object can solve the above problems.

What's a promise object

A promise object can be understood as an action that will be performed at a time and can be used by a chain call after a promise object is used

To organize your code so that code is more intuitive.

Resolve and reject

Read the code:

 function helloWorld (ready) {
 return new Promise(function (resolve, reject) {
 if (ready) {
 resolve("Hello World!");
 } else {
 reject("Good bye!");
 }
 });
 }
 helloWorld(true).then(function (message) {
 alert(message);
 }, function (error) {
 alert(error);
 });

In the above code implementation, the helloword function takes a parameter, if true, prints"hello world!"

If false, print the wrong information. A helloword function returns a promise object.


There are two important methods to resolve and reject in the promise object.


The resolve method can change the state of the promise object to success and pass one parameter for subsequent successful operations.

In this example, the hello world! string.


The reject method is to change the state of the promise object to a failure and pass the wrong information to the subsequent error handling.

then

The promise object has three states:
1. Fulfilled can be understood as a successful state.
2. Reject can be understood as a failed state.
3. Pending fulfilld is neither a nor a rejected state; you can unde & tand the initial state of a promise object I & tance creation.


The then method in the example of hello world is to determine the action that's performed according to the state of the promise object, and the first

Function ( onFulfilled ), execute the second function ( onRejected ) when reject. The promise mode is in one of three states at any time: Not completed ( unfulfilled ), completed ( address ) and rejected ( rejected ). As an example of commonjs promise/a, the then method on a promise object is respo ible for adding a handler for the completed and deny status. A then method returns back to another promise object so that it can be used to form a promise pipeline that enables developers to series asynchronous operations, such as then ( resolvedhandler, rejectedhandler ). A resolvedhandler callback function fires when the promise object enters the completion state and passes the result; A rejectedhandler function is invoked under rejected state.

Example code 1:

function printHello (ready) {
 var promise = new Promise(function (resolve, reject) {
 if (ready) {
 resolve("Hello");
 } 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);
 });;

Function first executes printHello and returns a promise object that concatenated the asynchronous operation through then.
Execution results 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-native/master/docs/MoviesExample.json';
 return fetch(REQUEST_URL)
. then((response) => response.json())
. then((responseData) => {
 var movie = 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);
 });

There are two promise in the above code, and the first promise is printHello, followed by the next then,

This then returns a promise for the data, and the promise of the later then is to point to the promise of this promise. The above example prints out the corresponding content in sequence by means of chain invocation. How then can use chain calls is because you always return a promise object every time that the method is executed. In addition, the return value of the function in then onFulfilled can be used as a parameter for subsequent operations.

catch

A then method is a simple way of writing onRejected functions in ( onFulfilled, onRejected ) methods.

Can be written as then ( fn ). Catch ( fn ), equivalent to then ( fn ), then ( null, fn ). Using catch is more clear than normal writing.

Beginners use easy error 1. Forget to add a catch ( ) method.

It's a very common mistake. Many programmers are confident that the promise calls in their code are very confident that the code never throws an error,

It's also possible that they simply forget to add a catch ( ) method. Unfortunately, no catch ( ) method will let the exception thrown in the callback function, and.

In your console, you can't see the error, which is very painful for debugging.

To avoid this bad situation, I've made a habit of adding the following code at the end of your promise call chain:

 somePromise().then(function () {
 return aPromise();
 }).then(function () {
 return anotherPromise();
 }).catch(function(error){
 console.log(error);
 });

Even if you don't want to handle exceptions in your code, adding catch ( ) in code is also a style of programming. In some cases,

When your original assumption is wrong, it'll make your debugging work easier.

Confusion of 2. Return.

Inside the then method, we can do three things:
1. Return a promise object.
2. Return a synchronous value or undefined.
3. throw an error.

After understanding the three cases, you'll understand the promise.

1. Return another promise object.


In related articles about promise, this writing is common, like a piece of code that forms a promise chain as mentioned above:

 getUserByName('nolan').then(function (user) {
 return fetch(REQUEST_URL)
. then((response) => response.json())
. then((responseData) => {
 } 
 }).then(function () {
 });

2. Returns a specific value or is 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 isn't called, the function in JavaScript returns undefined. That means that when you want to return some values,

No explicit calls to return will result in some side effects.

For the above reasons, you've made a that's always explicitly called return or throw in the then method. I also recommend that you do this.

3. Throw an error.

To throw it, it reflects the powerful capabilities of the promise. In the case where the user exits, our code will be handled in the way that an exception is thrown:

 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 is logged out, catch ( ) will receive an error if the state of the promise object becomes rejected.

It'll also receive an error.


Throwing exceptions when using a promise is useful in the development phase, which helps us locate errors in code. For example,

Calling JSON.parse ( ) inside the then function, and if the json object isn't legal, it may throw an exception, in the callback function, the exception is.



Author:
Link: http://www. Jianshu. com/p/174d9892283f.
source: simple book



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs