javascript - How do I use promises in node.js to clean up a chain of callbacks? -


i'm trying figure out how use promises, particularly q implementation clean messy nested callbacks in node.js program. unfortunately, there seems few simple examples out there illustrate i'd do.

here simplified version of nested callbacks have now:

    var parent = this;     this.receivemessage(params, function(err, request) {     if (err) console.log(err, err.stack);     else {        parent.handlemessage(request, function(response) {            parent.sendmessage(json.stringify(response), function() {                console.log("response sent");                var params = { receipthandle:request.messages[0].receipthandle };                parent.deletemessage(params, function() {                    parent.waitformessage();                });            });        });     } }); 

as can see pretty messy , has 4 levels of nested callbacks.

using q, i've figured out start like:

q.nfcall(this.connection.receivemessage, params)     .then(function(err, request) {         return(q.nfcall(this.handlemessage(request));     })     .then(function(response)) {          return(q.nfcall(this.sendmessage(json.stringify(response))));     } ... 

and on... doesn't seem quite right. first, need call q.nfcall on each function in chain? also, avoid scoping issues "this" when use callbacks? using promises correct way?

i had similar issues , realized later because of q. in opinion q has messy api , it's cumbersome use few simple examples. recommend trying other library, though recommend bluebird. bluebird following:

var promise = require('bluebird'); var parent = this; promise.promisifyall(parent, { suffix: "p" }); parent.receivemessagep(params)   .then(function (request) {     return [request, parent.handlemessagep(request)];   })   .spread(function (request, response) {     return [request, parent.sendmessagep(json.stringify(response))];   })   .spread(function (request) {     console.log("response sent");     var params = { receipthandle: request.messages[0].receipthandle };     return parent.deletemessagep(params);   })   .then(function () {     parent.waitformessage();   })   .catch(function (err) {     console.log(err, err.stack);   }); 

if don't style of returning arrays , using .spread, can use mapping object in outer scope.

var promise = require('bluebird'); var parent  = this; promise.promisifyall(parent, { suffix: "p" }); var cache = {}; parent.receivemessagep(params)   .then(function (request) {     cache.request = request;     return parent.handlemessagep(request);   })   .then(function (response) {     return parent.sendmessagep(json.stringify(response));   })   .then(function () {     console.log("response sent");     var params = { receipthandle: cache.request.messages[0].receipthandle };     return parent.deletemessagep(params);   })   .then(function () {     parent.waitformessage();   })   .catch(function (err) {     console.log(err, err.stack);   }); 

if need access variables later in chain resolved earlier in chain, can keep adding them cache object easy access. if have lot of those, method cleaner , easier read. prefer first example in cases, avoid polluting parent scope , potentially holding onto references should otherwise disposed of.

not can't similar promisifyall in q, bluebird more performant , more intuitive.

if callbacks don't conform typical node style signature of function (err, successvalue) (which of yours don't appear to, means promisifyall won't work on them) can define custom "promisifier" in bluebird. either or modify callback api conform node-style callbacks.

https://github.com/petkaantonov/bluebird/blob/master/api.md#option-promisifier


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -