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