Use of Promise in JavaScript

Source: Internet
Author: User
Promise, I believe that every front-end engineer has been used in projects more or less. After all, it is no longer a new term. ES6 has been supported by native, search Promise in caniuse, and find that the new version of chrome and firefox are also supported. But for earlier browsers we can use the polyfill library of es6-promise for compatibility. Promise is a function in ES6 that standardizes how to handle callback functions of asynchronous tasks. The function is similar to jQuery's defferred. Simply put, different callback functions are called through different states of the promise object. Currently, IE8 and earlier are not supported. other browsers support this function.

After the State of the promise object is changed from Pending to Resolved or Rejected, the state of the promise object will no longer change.

Procedure:

Var promise = new Promise (function (resolve, reject) {// asynchronous task, by calling resolve (value) or reject (error) to change the state of the promise object; the method for changing the status can only be called here. // When the promise status changes, the corresponding callback method will be called}); promise. then (function (value) {// callback function for resolve, parameters are passed in by asynchronous functions }). catch (function (error) {// callback function when an exception occurs or when reject () is clear })

Specific use:

Function getURL (URL) {// because the promise is executed when it is created, the factory function is used to encapsulate the promise object return new Promise (function (resolve, reject) {var req = new XMLHttpRequest (); req. open ('get', URL, true); req. onload = function () {if (req. status = 200) {resolve (req. responseText);} else {reject (new Error (req. statusText) ;}}; req. onerror = function () {reject (new Error (req. statusText);}; req. send () ;}) ;}// run the sample var URL = "http://httpbin.org/get"; getURL (URL ). then (function onFulfilled (value) {console. log (value );}). catch (function onRejected (error) {console. error (error );});

The callback of Promise is only asynchronous, And the callback of a synchronization task is also asynchronous.

Var promise = new Promise (function (resolve) {console. log ("inner promise"); // execute 1: The synchronization task first executes resolve ('callback');}); promise. then (function (value) {console. log (value); // execution 3: although the status is resolved during registration, the callback is still asynchronous;}); console. log ("outer promise"); // execute 2: run the synchronization code first.


Promise method chain

The callback registered by the then method is called in sequence, and parameters are passed between each then method using the return value. However, exceptions in the callback result in skipping the then callback, directly calling the catch callback, and then continuing to call the remaining then callback. In then (onFulfilled, onRejected), onFulfilled exceptions are not captured by their own onRejected, so catch is preferred.

Promise. then (taskA). then (taskB). catch (onRejected). then (finalTask );

If task Ka throws an exception and task KB is skipped, finalTask is still called because the promise object returned by catch is in the resolved state.

Three values can be returned in the then method.

1. Return another promise object. The next then method selects the onFullfilled/onRejected callback function for execution based on its status. The parameters are still transmitted by the resolv/reject method of the new promise;

2. returns a synchronous value. The next then method follows the current promise object state. You do not need to wait until the end of the asynchronous task is executed immediately. The real parameter is the return value of the previous then. If no return is returned, undefined is returned by default;

3. throw an exception (synchronous/asynchronous): throw new Error ('xxx ');

Then not only registers a callback function, but also transforms the return value of the callback function, creates and returns a new promise object. In fact, Promise operations in the method chain are not the same promise object.

var aPromise = new Promise(function (resolve) {  resolve(100);});var thenPromise = aPromise.then(function (value) {  console.log(value);});var catchPromise = thenPromise.catch(function (error) {  console.error(error);});console.log(aPromise !== thenPromise); // => trueconsole.log(thenPromise !== catchPromise);// => true

Promise. all () static method, multiple asynchronous tasks at the same time. After all received promise objects are in the FulFilled or Rejected state, subsequent processing will continue.

Promise. all ([promiseA, promiseB]). then (function (results) {// results is an array, and the element value corresponds to the previous promises object}); // The array composed of promise objects is executed simultaneously, instead of sequential execution, the start time is basically the same. Function timerPromisefy (delay) {console. log ('start time: "'+ Date. now () return new Promise (function (resolve) {setTimeout (function () {resolve (delay) ;}, delay) ;}var startDate = Date. now (); Promise. all ([timerPromisefy (100), // promise packs timerPromisefy (200), timerPromisefy (300), timerPromisefy (400)] in factory form). then (function (values) {console. log (values); // [100,200,300,400]});

Execute promise one by one instead of at the same time.

// Promise factories returns the promise object. The next thenfunction sequentialize (promiseFactories) {var chain = Promise is executed only when the current asynchronous task ends. resolve (); promiseFactories. forEach (function (promiseFactory) {chain = chain. then (promiseFactory) ;}); return chain ;}

Promise. race () is similar to all (). However, if a promise object enters the FulFilled or Rejected state, the corresponding callback function is executed. However, after the first promise object becomes Fulfilled, the execution of other promise objects will not be affected.

// Use Promise. example of all () Promise. race ([timerPromisefy (1), timerPromisefy (32), timerPromisefy (64), timerPromisefy (128)]). then (function (value) {console. log (values); // [1]});

Promise. race () as a timer

Promise.race([  new Promise(function (resolve, reject) {    setTimeout(reject, 5000);     // timeout after 5 secs  }),  doSomethingThatMayTakeAwhile()]);

Changing promise status in then

Because the then callback only contains the value parameter, there is no method to change the state (only used in the asynchronous task of the constructor method), to change the state of the promise object passed to the next then, you can only create a new Promise object, judge whether the State is changed in the asynchronous task, and finally return to the next then/catch.

Var promise = Promise. resolve ('xxx'); // method of promise object creation promise. then (function (value) {var pms = new Promise (function (resolve, reject) {setTimeout (function () {// check whether the State reject/resolve Reject ('args') ;}, 1000) ;}) return pms; // The promise object can have a new state, the next then/catch must wait until the asynchronous end to execute the callback. If the common value/undefined is returned, the subsequent then/catch will be executed immediately }). catch (function (error) {// call the console when the object is reject. log (error )});

Obtain the results of two promises

// Method 1: Pass var user in the outer variable; getUserByName ('nolan '). then (function (result) {user = result; return getUserAccountById (user. id );}). then (function (userAccount) {// you can access user and userAccount}); // Method 2: The last then method mentions getUserByName ('nolan') in the previous callback '). then (function (user) {return getUserAccountById (user. id ). then (function (userAccount) {// you can access user and userAccount });});


Note the overall structure when using promise

Assume that both doSomething () and doSomethingElse () return the promise object.

Common Methods:

DoSomething (). then (doSomethingElse ). then (finalHandler); doSomething | --------------- | doSomethingElse (updated) // return a new promise. The next then will be executed only after receiving the new status. | ------------------ | finalHandler

Common workarounds:

DoSomething (). then (function () {return doSomethingElse ();}). then (finalHandler); doSomething | ----------------- | equals (undefined) // arguments [0] of the then outer function = bytes | ---------------- | finalHandler (handler) | ---------------- |

Error Method 1:

DoSomething (). then (function () {doSomethingElse ();}). then (finalHandler); doSomething | --------------- | doSomethingElse (undefined) // although doSomethingElse returns the promise object, the callback function of the outermost layer is return undefined, therefore, the next then method will immediately execute a callback without waiting for the new promise status. | ---------------- | FinalHandler (undefined) | ------------------ |

Error Method 2:

DoSomething (). then (doSomethingElse ()). then (finalHandler); doSomething | ----------------- | doSomethingElse (undefined) // The callback function is called directly at registration. | ---------- | finalHandler (handler) | ---------------- |

For more articles about using Promise in JavaScript, refer to the PHP Chinese website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.