ES6 Promise objects and solve the problem of callback hell

Outline

In the JavaScript world, all code is single-threaded execution.

Because of this "defect", causing all network operations, browser events JavaScript, must be executed asynchronously.

AJAX is a typical asynchronous operation.

The callback function success(request.responseText)and fail(request.status)wrote an AJAX operation in normal, but does not look good, but also not conducive to code reuse.

Is there a better way? For example, written like this:

var ajax = ajaxGet('http://...');
ajax.ifSuccess(success)
    .ifFail(fail);

First uniform implementation of AJAX logic, do not care about how to deal with the results, then, according to the results of success or failure, calling at some point in the future successfunction or failfunctions. This "committed to the implementation of the future" of the object called Promise objects in JavaScript.

Examples

We look at a simple example of Promise: generating a random number between 0 and 2, if less than 1, waiting to return to success after a period of time, otherwise fail:

function test(resolve, reject) {
    var timeOut = Math.random() * 2;
    console.log('set timeout to: ' + timeOut + ' seconds.');
    setTimeout(function () {
        if (timeOut < 1) {
            console.log('call resolve()...');
            resolve('200 OK');
        }
        else {
            console.log('call reject()...');
            reject('timeout in ' + timeOut + ' seconds.');
        }
    }, timeOut * 1000);
}

 

As can be seen, test()function only concerned with its own logic, do not care about the specific resolveand rejectwill process the results.

With the execution of the function, we can use a Promise object to execute it, and success or failure of the results at some future time:

var p1 = new Promise(test);
var p2 = p1.then(function (result) {
    console.log('成功:' + result);
});
var p3 = p2.catch(function (reason) {
    console.log('失败:' + reason);
});

Promise objects can be strung together, the above code can be simplified to:

new Promise(test).then(function (result) {
    console.log('成功:' + result);
}).catch(function (reason) {
    console.log('失败:' + reason);
});

Promise biggest benefit is seen in the process of asynchronous execution, the execution code and the code of processing results clearly separated:

 

 

Promise.all () these two tasks can be executed in parallel

var P1 = new new Promise ( function (Resolve, Reject) { 
    the setTimeout (Resolve, 500, 'Pl' ); 
}); 
var P2 = new new Promise ( function (Resolve, Reject) { 
    the setTimeout (Resolve, 600, 'P2' ) ; 
}); 
// performed simultaneously p1 and p2, and they are performed after completion of the then: 
Promise.all (. [p1, P2]) the then ( function (Results) { 
    the console.log (Results); // get a the Array: [ 'Pl', 'P2'] 
});

Promise.race () multiple asynchronous tasks to fault-tolerant, just need to get the first results to be returned.

var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 600, 'P2');
});
Promise.race([p1, p2]).then(function (result) {
    console.log(result); // 'P1'
});

Promise state

Promise asynchronous operation has three states: pending (in progress), fulfilled (been successful) and rejected (failed). In addition to the results of an asynchronous operation, no other operations can change that state.

Promise only objects: from pending changes to become fulfilled and rejected the pending state changes. As long as fulfilled in and rejected, the state will not have changed that is resolved (finalized).

then method

then method receives two functions as parameters, the first parameter is a callback when the Promise of success, the second parameter is a callback when the Promise fails, there will only be a two functions is called.

Prior to the completion of the currently running JavaScript event queue, the callback function is never called.

By  adding .then form callback function, no matter what, it will be called.

 

The callback function VS Promise

之前大家解决异步事件都是用回调函数去解决,但是回调函数写异步会出现一些问题,回调地狱的问题。

那么promise就是一种新的处理异步的方法,可以完美的解决回调函数处理异步带来的问题(回调地狱问题)。

其实promise就是异步操作的方法,就像之前的定时器一样,看到定时器就知道这是异步操作,同样,看到promise就知道这个是异步操作。
 
Hell callback problem
When using the JavaScript, in order to achieve some logical write often deeply nested callback function, if too much nested, will greatly affect the code readability and logic, this is also known as callback hell. Code reader is poor.
For example, when the user logs in, first verify user information and returns, after obtaining the user information to get the number of gold coins, as well as the relevant rights of users and other user information. It is easy to form the callback hell. (Note Liang Tao)
var sayhello = function (name, callback) {
  setTimeout(function () {
    console.log(name);
    callback();
  }, 1000);
}
sayhello("first", function () {
  sayhello("second", function () {
    sayhello("third", function () {
      console.log("end");
    });
  });
});
//输出: first second third  end

There are many ways to solve the callback hell, such as: Promise objects, Generator function, async function

Promise objects to solve the callback hell

var sayHello = function (name) {
   return  new new Promise ( function (Resolve, Reject) { 
    the setTimeout ( function () { 
      the console.log (name); 
      resolve ();  // execution resolve () function after the asynchronous operation is performed 
    } , 1000 ); 
  }); 
} 
sayHello ( "First") the then (. function () {
   return sayHello ( "SECOND");  // still returns a Promise objects 
.}) the then ( function () {
   return sayHello ( "THIRD " ); 
}) the then (. function () {
  console.log('end');
}).catch(function (err) {
  console.log(err);
})

 

Refer to the original  reference text 2

Guess you like

Origin www.cnblogs.com/liangtao999/p/11716866.html