Javascript Promise Getting Started

Source: Internet
Author: User
Tags deprecated readfile

What is it?

https://www.promisejs.org/

What is
a promise?

The core idea behind promises is, a promise represents the result of an asynchronous operation. A promise is in one of three different states:

  • Pending-the initial state of a promise.
  • Fulfilled-the State of a promise representing a successful operation.
  • Rejected-the State of a promise representing a failed operation.

Once a promise is fulfilled or rejected, it's immutable (i.e. it can never change again).

The core idea of promise is that promise can represent the result of an asynchronous operation. Includes three states, pending, Fulfiled, rejected

Promise in English is a promise, fulfil promise for the realization of the promise, rejected promise to take back the promise. Each indicates success and failure.

Using promise to describe the results of asynchronous operations is too image, in the present definition of a promise, the result of the promise, need to be verified in the future, does not affect the current operation plan,

For example, you say to your wife, you will have to buy a big house for your wife to live in the future. When you say, do not affect your day or tomorrow's work and life plan, the code is coded, the walk on the walk,

As for the future can not buy a big house, that is later things, of course, the promise to have a deadline, the deadline has arrived, according to the promise, need to buy a house, if can buy fulfill promise, if not realized, then reject promise.

As in the following example:

A promise that reads a file is defined, the read succeeds calling the fulfill callback, and the read fails to invoke the reject callback.

function readFile (filename, enc) {  returnnew Promise (function  (fulfill, reject) {     function (Err, res) {      if  (err) reject (err);       Else Fulfill (res);});}  );

Why?

If there is no promise, for example, in the above example, the asynchronous read action, we need to handle various error conditions, and success conditions in our callback function callback.

Error conditions, including:

1. Failed to read file

2. Failed to parse read data

Success situation:

1. Parse Read data successfully

After using promise, for a successful case, define a successful handler function, and for a failure, define the failed handler. Code logic is exceptionally clear.

function Readjson (filename, callback) {  function  (err, res) {    ifreturn callback (ERR);     Try {      = json.parse (res);     Catch (ex) {      return  callback (ex);    }    Callback (null, res);  });

How to use it?

In addition to the first section, we construct a promise example that specifies that you want to specify the fulfill and reject callback functions, and if you want to do some other action after the asynchronous operation is complete, you can define it by invoking the following interface:

Use .then whenever your ' re going to does something with the result (even if, s just waiting for it to finish)

Use .done whenever aren ' t planning in doing anything with the result.

function Readjson (filename) {  return readFile (filename, ' UTF8 '). Then (function  (res) {     return Json.parse (RES)}  )}

To combine then and catch interfaces, examples of implementations:

Https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

var New Promise (function(resolve, reject) {  Resolve ("success");}); P1.then (function(value) {  //  "Success!"  Throw "Oh, no!" ;}). Catch (function(e) {  //  "Oh, no!"});

jquery Ajax implementations

https://api.jquery.com/jQuery.ajax/#jqXHR

$.ajax ({  "http://fiddle.jshell.net/favicon.png",  function(XHR) {    "Text/plain; Charset=x-user-defined " );  })  . Done (function(data) {    if (console && console.log) {      
     "Sample of Data:", Data.slice (0, +) );    }  );

Api

  • Jqxhr.done (function (data, textstatus, JQXHR) {});

    An alternative construct to the success callback option, refer to for deferred.done() implementation details.

  • Jqxhr.fail (function (JQXHR, textstatus, Errorthrown) {});

    An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to for deferred.fail() implementation details.

  • Jqxhr.always (function (DATA|JQXHR, textstatus, Jqxhr|errorthrown) {});

    An alternative construct to the callback option, the .always() method replaces the deprecated .complete() method.

    In response to a successful request, the function ' s arguments is the same as those .done() of: data, Textstatus, and the JQ XHR object. For failed requests the arguments is the same as those .fail() of: The Jqxhr object, Textstatus, and Errorthrown. Refer to for deferred.always() implementation details.

  • Jqxhr.then (function (data, textstatus, JQXHR) {}, function (JQXHR, textstatus, Errorthrown) {});

    Incorporates .done() .fail() the functionality of the and methods, allowing (as of jQuery 1.8) The underlying Promise to be MA Nipulated. Refer to for deferred.then() implementation details.

Promise API Standard

https://www.promisejs.org/api/

Each API has a simple introduction to use, it is easy to understand, I like it.

varP1 =NewPromise (function(Resolve, Reject) {Resolve ("Success");}); P1.then (function(value) {Console.log (value);//"success!"  Throw"Oh, no!.";}).Catch(function(e) {console.log (e);//"Oh, no!."}); SetTimeout (function() {P1.then (function(value) {Console.log (value);//"success!"  Throw"Oh, no!.";}). Then (Undefined,function(e) {console.log (e);//"Oh, no!."});}, 2000)

Javascript Promise Getting Started

Related Article

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.