When you jump out of async callback Nightmare node. JS under promise/a specification usage

Source: Internet
Author: User

In fact, about promise blog, the front-end time dedicated to write a promise specification of the article, Promise specification makes JavaScript in the asynchronous call more humane.

Simple recall under:

The "deferred/promise" model defined by the PROMISE/A specification

In fact, the "Publish/Subscribe" model is implemented.

Publish events through the deferred object,

Includes the following 2 types of events

Finish-to-resolve event,

Failed--Reject event,

Subscriptions that correspond to completion or failure through the Promise object

Events are triggered, similar to the task state transitions.

The execution event binding function will be corresponding.

There are three states for each promise task:

Default (Pending), Finish (fulfilled), failure (rejected)

1. The default state can be transferred one-way to the completion state, the process is called resolve, the corresponding method is Deferred.resolve (Value);

2. The default state can also be transferred one-way to the failed state, the process is called reject, the corresponding method is deferred.reject (reason);

3. The default state, you can also use Deferred.notify (message) To announce task execution information, such as execution progress;

4. The transfer of state is one-time, once the task is changed from the initial pending to other States, it will go into the execution of the next task.

Today is actually want to share with you next when this NPM package, perhaps in the future you will use.

GitHub Address: Https://github.com/cujojs/when

We use a concrete simulation example to learn when

Application Scenarios:

If I have a service, run it regularly every day.

What is the task to do, is to go to the securities/bank site to read the day's exchange rate information, and then save to their own database.

The logic is simple:

    1. See if you have the latest exchange rate information on the day

    2. If available, get exchange rate information

    3. If you get to, save to the local database

We define 3 methods in turn:

Get the exchange rate information function get (callback) {///specific request URL, parse DOM all omitted, all when called the following a black box method to implement Yijiebuyi_util.gethtml (' http://aaa.com/bbb '    , function (Err,info) {callback (err,info); });}
Save Exchange rate Information function Save (info,callback) {//Write database method ignores Yijiebuyi_util.save (Info,function (Err,result) {Callback (Err    , result); });}

OK, let's start with a normal call method

function main (callback) {    //Get exchange rate information      get (function (err,info) {       if (err) {            return callback (err,null);        }        //Save exchange rates Information        save ( Info,function (Err,result) {           if (err) {                return callback (Err, NULL);           }            //Callback Save Status             Callback (null,result);        });     }); 

If the business is more complex, a layer of nesting, it looks like it is not very good to wait until maintenance time may be laborious.

Some people say that it is possible to use async to control, and we generally do.

Async can control the entire process, such as in-line execution, the next execution function uses the previous step to execute the result, and so on.

But today we recommend a solution that looks elegant.

We jump out of the process, do not control the business in the process, but start with each business method and let the method build a promise specification by when.

We still have to modify all of the above methods:

Install first, apply when

NPM Install-g when

var when=require (' when ');
function get () {    var deferred =  When.defer ();     yijiebuyi_util.gethtml (' http://aaa.com/bbb ', function (err,info) {         if (ERR)              deferred.reject (ERR);        else             deferred.resolve (Info);                     return  deferred.promise;    });} 
function Save (info,callback) {var deferred = When.defer ();        Yijiebuyi_util.save (Info,function (Err,result) {if (err) deferred.reject (err);                    else deferred.resolve (result);    return deferred.promise; });}

We have modified the above 2 methods to see how the Main method is called.

function Main () {get (). Then (save). catch (function (err) {Console.log (err); });}

We do not control the order of business logic processing on the process. Instead, it's nice to call it in the same order as the synchronous code does.

The then method consists of three parameters,

Onfulfilled,

Onrejected,

OnProgress

Promise.then (onfulfilled, onrejected, OnProgress)

From the parameter name you can see that these methods should be event handlers.

This is also what we said above, promise itself is an event publish/subscribe model.

So the three functions above then are equivalent to the event binding function. (is the observer)

When the previous task is deferred.resolve (data), corresponding to this task will trigger the Onfulfilled method.

When the previous task is deferred.reject (err), the corresponding task will trigger the Onrejected method.

Any one task, the onfulfilled or Onrejected method can only be triggered one, and is triggered once.

The last catch in our main method above (function (Err) {...}) is going on.

When providing a very simple delivery error mechanism, when multiple tasks are executed, we can define the onrejected in the last task

or catch the error at the end of the then call.

end***

When you jump out of async callback Nightmare node. JS under promise/a specification usage

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.