node.js - What is the best way to loop bluebird promises -
now i've working on nodejs , sequelize query , process database data. i've call findall table1 , want query each rows apply data table2 want add data array before send output, did this
var last_promise; var output_results = {}; table1model.findall() .then(function(results1) { (var = 0; < results1.length; ++i) { var result1 = results1[i]; output_results[result1.id] = result1; var add_promise = table2model .create({ id_from_table1: result1.id, data_from_table1: result1.data }); .then(function(result2) { output_results[result2.id_from_table1].data2 = result2; }); if (last_promise) { last_promise.then(function() { return add_promise; }); } else { last_promise = add_promise; } } } } last_promise.then(function() { return output_results; }
i want know there better way execute promises sequentially in loop ?
it looks can .all()
method:
table1model .findall() .then(function(results1) { return promise.all(results1.map(function(result) { return table2model .create({ id_from_table1: result1.id, data_from_table1: result1.data }) .then(function(result2) { ... }); })); }) .then(function(output_results) { });
Comments
Post a Comment