node.js - Javascript asynchronous calls chaining -
given array contains objects of type , b, b can transformed set of type objects, via asynchronous call, best way of transforming array objects array (transforming each b object in set of corresponding objects) , execute callback when bs transformed?
list = [a, b, a, b, a, a, b, a]; function transform (b, callback) { //transform b type object type objects array [a, a, a]..... callback([a, a, a]); } transformbobjectsintoaobjects(list, callback) { // ????????? callback(list); // should type objects }
well, need execute final callbacks after callbacks transformbtolist
have returned result. there multiple ways it:
count how many callbacks have passed away , decrement when call back, , know you're finished when counter has reached 0 again.
however, cumbersome, , there libraries it:
async.js well-known , easy use:
function transform(b, callback) { … } function transformbobjectsintoaobjects(list, callback) { async.map(list, function(x, cb) { if (x b) transform(x, cb) else cb([x]) }, function(results) { callback(concat(results)) } }
promises (there many implementations superior approach. might bit more complex understand, have nice properties , lead nice & concise syntax. in case, be
function transform(b) { // no callback! // async: resolve([a, a, a]); // see docs of promise library return promise; // exact reference } function transformbobjectsintoaobjects(list) { return promise.all(list.map(function(x) { return (x b) ? transform(x) : promise.resolve([x]); })).then(concat); }
Comments
Post a Comment