[node. js] Promise,q and Async

Source: Internet
Author: User
Tags readfile

Original address: http://www.moye.me/2014/12/27/promise_q_async/

Introduction

When programming with NODE/JS, you often encounter the problem of having a series of asynchronous methods that need to be executed sequentially, with dependencies between the results, such as (Fragment 1):

Asynctask (Initial,function(Err, result) {//Step 1    if(ERR)Throwerr; Asynctask (Result,function(Err, RESULT2) {//Step 2        if(ERR)Throwerr; Asynctask (RESULT2,function(Err, RESULT3) {//Final            if(ERR)Throwerr;        Console.log (RESULT3);    }); });});

Previously introduced, this is known as the callback Hell (Pyramid of Doom).

Promise

To solve the callback nesting and serial state transmission problems, there are norms to follow, such as the COMMONJS Promise specification.

Promise is an abstraction of asynchronous programming. It is a proxy object that represents the value or exception thrown by a function that must be processed asynchronously.

To achieve more promise/a (thenable):

    • Promise, as an object, represents the execution of a task, which has three states: success/failure/execution
    • The Promise object has a then interface (a prototype function) that is shaped like: then(fulfilledHandler, errorHandler, progressHandler) . These three parameters are executed when the Promise object completes the task, and they correspond to the status of success/failure/execution--we can equate the then method with the constructor of the Promise object, and fulfilledHandler errorHandler progressHandler can correspond to Promise.resolve(val) , Promise.reject(reason) andPromise.notify(update)
    • Promise object also has a Catch interface (prototype function), such as: catch(onRejected)。 onrejected for error handling callback, receive Promise.reject(reason) the error message from passing over
    • The Promise object is exposed to the caller's then interface, which is a function that can always return the Promise object itself, so then you can continue chaining to then until the task is complete--simply put, the result of promise execution can be passed to the next promise object. This is useful in the serialization of asynchronous tasks (and we do not have to worry about the side effects of these promise in the execution of the task, according to the specification, each of the promise and the tuned function is independent of each other.
    • Promise the inside of the object, maintains a queue and, when the construction execution chain completes, stores the pending function in the task that needs to be executed sequentially-when is it done? The General Promise Library implementation requires that a function such as done be called at the tail of the construction chain to express the end of the construction chain.

Promise as the details of classes and objects, the description on the MDN is more detailed. Back to the implementation level, first look at an open source promise framework, Q:

Q

Q is an open source framework that implements a more complete promise/a specification.

For the preceding code snippet 1 scenes, Q provides the possibility that q.promise can wrap the asynchronous logic into a thenable function that injects the callback function it implements, such as the source shape:

 q.promise = promise;  function   Promise (resolver) { if  (typeof  resolver!== "function" ) { throw< /span> new  TypeError ("Resolver must be a function.")    );     var  deferred = defer ();              try   {resolver (deferred.resolve,    Deferred.reject, deferred.notify);  catch   (reason) {Deferred.reject (Reaso    n);  return   deferred.promise;}  

This resolver is our asynchronous logic wrapper function, we can selectively receive resolve and reject as parameters, and in asynchronous method completion/error callback, let Q get Process control.

Asynchronous serial example of Q

Suppose there are two text files: 1.txt and 2.txt, and the contents are: I‘m the first text.\n and I‘m the second text.\n . We need to read them sequentially and asynchronously, displaying the corresponding information when all reads are complete/faulted.

First, you need to wrap the Async method:

varQ = require (' q '));varPath = require (' path ');varFS = require (' FS ');functionReadFile (Previous, fileName) {returnQ.promise (function(Resolve, Reject) {Fs.readfile (Path.join (PROCESS.CWD (), fileName),function(Error, text) {if(Error) {Reject (Newerror (Error)); } Else{Resolve (previous+text.tostring ());    }            }); });}

Fs.readfile read the file, successfully called Q.defer.resolve, error called Q.defer.reject. ReadFile as a method for concatenating promise objects, provides a previous state parameter that is used to accumulate the results of the last execution. With this approach, then-based serial logic can be implemented:

ReadFile (', ' 1.txt ')    . Then (function  (previous)        {return readFile ( Previous, ' 2.txt ');    })    . Then (function  (finaltext) {        console.log (finaltext);    })    . Catch (function  (error) {        console.log (error);    })    . Done ();

As you can see, a chained call to the Thenable function always passes the result of the previous promise.resolve as a parameter.

Async

Async Strictly speaking is not a promise implementation, but an asynchronous toolset (utilities), through the source we can see very clearly, it exported a lot of methods, the collection/process control are involved.

For the preceding code snippet 1 scenes, Async provides several ways to pick two representative:

Async.waterfall

Waterfall waterfall(tasks, [callback]) , Tasks is a function array, and the [callback] parameter is the callback for the final result. The functions in the tasks array can receive the results of the previous task execution, and see an example:

varAsync = require (' async ');varPath = require (' path ');varFS = require (' FS ');functionReadfile4waterfall (Previous, filename, callback) {Fs.readfile (Path.join (), filename),function(Error, text) {Callback (Error, previous+text.tostring ()); });} Async.waterfall ([function(callback) {Readfile4waterfall (', ' 1.txt ', Callback)},function(Previous, callback) {Readfile4waterfall (Previous,' 2.txt ', callback); }    ], function(err, result) {Console.log (result); });

As you can see, no matter what form of asynchronous process control, you need to inject the implementation callback (here is the function (callback)) to get control of the process. Operation Result:

I'm the first text. I'm the second text.
Async.series

Series like waterfall(tasks, [callback]) , unlike waterfall, the functions in the tasks array accept only one callback injection, and cannot pass the results of the last task execution. The results of each function execution are push into a result array, which is the second parameter of [callback (error, result)]. Example:

varAsync = require (' async ');varPath = require (' path ');varFS = require (' FS ');functionreadfile4series (filename, callback) {Fs.readfile (Path.join (PROCESS.CWD (), filename),function(Error, text) {Callback (Error, text.tostring ()); });} Async.series ([function(callback) {readfile4series (' 1.txt ', Callback)},function(callback) {readfile4series (' 2.txt ', callback); }    ], function(err, result) {Console.log (result); });

Operation Result:

' i\ ' m the first text.\n ' ' I\ ' m the second text.\n ' ]

More articles please visit my blog new address: http://www.moye.me/

[node. js] Promise,q and Async

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.