node. JS Promise maintains (synchronizes) multiple callback (async) states

Source: Internet
Author: User

Jintiansheng: To learn a new thing, it is necessary to hold a hug mentality, if cling to their previous concept system, there will be a difficult feeling.
. NET programmer first with node. JS is the most need to adapt to asynchronous development, all asynchronous, the general logic of the traversal of the list is asynchronous, how to ensure that the list traversal execution is complete? Promise help you get it done!
Jintiansheng: 15998603918 Welcome to chat with me.

node. JS programming, exclusively callback.

If there is no promise, a series of business logic, from the first step back to the last step, "single-threaded Logic" also make, encounter "multithreading logic", then into a callback hell.

Since the promise, everything is not a problem!

Examples of application scenarios:

In a request complete the query Monogodb all collection and count the number of document.

Specific query logic
1. ListDatabases (callback)

2. Traverse Collections, check the number of documents separately, COUNT (callback)

3. Return to collections.

Code:

Function (req, res) {    var db = ms.connection.db;    var tables = Db.listcollections (). ToArray ();    The Promise#then callback is a regular notation, but still executes asynchronously    Tables.then (function (RS) {        var ps = [];        Rs.foreach (function (collection) {            Ps.push (db.collection (collection.name). Count (). Then (function (count) {                Collection.itemcount = count;            });        });                Promise.all ensures that all collection.itemcount are queried, playing the role of synchronous        Promise.all (PS). then (function () {            res.send (RS);        });    });}

The above is a non-complete code, can not be used directly, as the relevant business ideas, solutions for reference.

node. JS Promise maintains (synchronizes) multiple callback (async) states

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.