First, what Promise that?
var sayhello = function (name, callback) { setTimeout(function () { console.log(name); callback(); }, 1000); } sayhello("first", function () { sayhello("second", function () { sayhello("third", function () { console.log("end"); }); }); }); // output: first second third end
promise is used to solve two problems:
- Callback Hell, hard to maintain the code, is often a function of the output of the first input of the second function of this phenomenon
- promise can support multiple simultaneous requests, concurrent data acquisition request
- This promise can solve the asynchronous problem itself can not say that promise is asynchronous
Two, es6 promise usage Daquan
Promise is a constructor, himself a all, reject, resolve these familiar ways, there is then, catch methods on the prototype.
let p = new Promise((resolve, reject) => { // do some asynchronous operation setTimeout(() => { the console.log ( 'execution completion'); resolve ( 'I was successful !!'); }, 2000); });
- resolve: asynchronous operation callback function after success
- reject: the asynchronous operation failed callback function
Usage then chain operations
Therefore, on the surface, but can be simplified Promise layers callback written, but essentially, is the essence of Promise "state", a way to maintain state, so that the transmission state to timely callback call, which transfer the callback function than It should be simple, flexible and more. So use the correct scene Promise is this:
p.then( (data) => { console.log(data); }) .then( (data) => { console.log(data); }) .then( (data) => { console.log(data); });
reject usage:
The Promise flag as rejected, so that we can capture in then, and then execute the callback case of "failure." Look at the following code.
let p = new Promise((resolve, reject) => { // do some asynchronous operation setTimeout(function(){ var num = Math.ceil (Math.random () * 10); // generates a random number 1-10 if(num<=5){ Resolved (a); } else{ Reject ( 'Digital too large'); } }, 2000); }); p.then((data) => { console.log('resolved',data); },(err) => { console.log('rejected',err); } );
catch usage
We know that in addition to then subject Promise method, there is a catch method, it is what to do with it?
In fact, it's the same as the second argument then, is used to specify a callback reject. Usage is like this:
p.then( (data) => { console.log('resolved' , data) }). catch( (err) => { console.log('rejected' , err) })
Effect and then write in the second parameter inside the same, but it also has a second role: When callback resolve (that is, the first parameter of the above then), if an exception is thrown (the code wrong) , it does not complain stuck js, but will enter into this catch method.
p.then( (data) => { console.log('resolved', data); console.log (somedata); // somedata defined herein }) .catch( (err) => { console.log('rejected', err) })
In the callback resolve, we console.log (somedata); and somedata this variable is not defined. If we do not Promise, to run the code directly in the console error here, you do not run down. But here, you get this result:
That went in to catch a method to go, but the cause of the error spread to the reason parameter. Even if there is an error code is not being given, which is our try / catch statement has the same functionality
all usage: Who is running slow, in order to perform the callback who prevail.
receiving an array of all parameters, which is considered the value of the final target returns Promise
Promise of all parallel method provides the ability to perform asynchronous operations, and complete execution before all asynchronous callback operation is performed.
See the examples below:
let Promise1 = new Promise( function(resolve, reject) { }); let Promise2 = new Promise( function(resolve, reject) { }); let Promise3 = new Promise( function(resolve, reject) { }); let p = Promise.all( [Promise1, Promise2, Promise3] ) p.then(function() { // success is the success of all three },{ // As long as there is a failure, then failure })
race usage: who run fast, in order to perform the callback who prevail
race usage scenarios: For example, we can use an asynchronous request race to set the timeout, and performs a corresponding operation after the timeout, as follows:
// request a picture resources function requestImg(){ var p = new Promise( (resolve, reject) => { img.onload = function(){ resolve(img); } img.src = 'image path'; }); return p; } // delay function, a request timing for function timeout() { var p = new Promise( (resolve, reject) => { setTimeout( () => { Reject ( 'Image Request Timeout'); },5000) }); return p; } Promise.race([requestImg(), timeout()].then( (data) =>{ console.log(data); }).catch( (err) => { console.log(err); }) )