1. Promise overview

Promise is a method that’s native to ES6 that represents something that’s going to happen in the future, and in javascript it’s an asynchronous operation, so in JS Promise is a common way of doing asynchronous operations,

Common methods of asynchronous operation:

Callback callback function 2 event listener 3 Promise 4 Publish/subscribe 5 Async /await 6 Generator chain call

Here we’ll focus on Promise

The main advantage of Promise is that asynchronous operations can be represented through the flow of synchronous operations, avoiding asynchronous nested callbacks. Create callback hell.

2. Make a promise

The promise object is a constructor with the following basic syntax:

var promise = new Promise (function (resolve,reject){
	if(success){
	resolve(value);
}else{ reject(error); }}); promise.then(function(value) {
//success
},function(value} / /failure
});
Copy the code

The resolve and reject arguments in this example are then called back to the corresponding callback function. This is the basic use of promise

3, The promise chain call

Chain calls are a concept introduced in JQ. Selectors in JQ are chain operations: eg:

  • $(‘#div’).css(‘background’,’#ccc’).removeClass(‘box’).stop().animate({width:300})

A chained call is a function that returns the result of its execution via return this, so that other functions can continue to be called

This is the chain call in JS

 function show(str) {
        console.log(str);
        return show;
    }
    show(123) (456) (789);
Copy the code

The object returned by then in a promise is the new object of the promise

getJSON ("/posts.json").then(function(json){
	return json.post;
}).then(function(post){
//proceed
});
Copy the code

In the code above, the first THEN callback returns json.post as an argument to the second THEN callback. The then method continues the result returned by calling the previous callback function.

4. Promise method

Catch A catch is actually an alias for the then (null, Rejection) callback that catches and throws an error when it occurs.

getJSON ("/posts.json").then(function(json){
	//code does not return
}).catch(function(error){
// The previous function did not return a result, so it could not be called
console.log("error!",error);
});
Copy the code

Any error that occurs during a THEN callback is thrown by a catch.

All promise. The all method wraps a new promise object from multiple then returns (as long as those returns are true).

var promise = [2.3.4.5.6.7].map(function(id){
	return getJSON("/poost/" + id +".json");
});
promise.all(promises).then(function(posts){
//....
}).catch(function(reason){
/ /...
});
Copy the code

In this code, use the all method to program the array returned above into a new one.

Resolve Promise. The resolve method converts an existing object into a promise object.

var jsPromise = Promise.resolve($.ajax('/whatever.json'));
Copy the code

5. Three states of promise

Pending: Initial state, not success or failure; This is a big pity. Rejected: indicates the failed state.

In promise, only the result of the asynchronous operation can change his state. Other operations cannot be changed. Once the state is changed, the state cannot be manually changed.

6, the difference between async await and promise

Async is an ES7 concept, promise is an ES6 concept so async is elegant and promises are just fulfilling promises.

After promise was proposed, it was not perfect enough to handle errors, so.catch and.finally were proposed to facilitate catching errors. It then generates generators in ES7. Async await there are a lot of things on the web that say async is a syntactic candy for generator and I think in the same way async is a syntactic candy for promise. It’s a refinement and upgrade of Promise

The state of the Promise returned by async functions will not change until all the Promise objects of the internal await command have been executed

To summarize: Async await is implemented based on a Promise, which is an improved Promise and cannot be used for ordinary callback functions. It also returns a Promise object. The problem solved and the effect achieved are similar, but async syntax is more concise.

7, Promise features

1. The Promise constructor executes immediately, and the code called by the promise.then method is called asynchronously. 3. Resolve and Reject methods both change the promise state to complete. The asynchronous result is then returned as an error argument. The promise constructor value is called once. Then and catch objects can be called multiple times. If they return a result, the result will be called the next time.

8, Promise shortcomings

1. The promise is immediately executed after it is established and cannot be cancelled. 2.