如何处理循环中的承诺?

这是我想要做的

var response = []; Model.find().then(function(results){ for(r in results){ MyService.getAnotherModel(results[r]).then(function(magic){ response.push(magic); }); } }); //when finished res.send(response, 200); 

但是它只返回[],因为asynchronous的东西还没有准备好。 我正在使用使用Q promise的sails.js。 任何想法如何在所有asynchronous调用完成时返回响应?

https://github.com/balderdashy/waterline#query-methods(promise方法)

由于水线使用Q ,所以可以使用allSettled方法。
您可以在Q文档中find更多详细信息 。

 Model.find().then(function(results) { var promises = []; for (r in results){ promises.push(MyService.getAnotherModel(results[r])); } // Wait until all promises resolve Q.allSettled(promises).then(function(result) { // Send the response res.send(result, 200); }); }); 

你根本无法做到这一点,你必须等待asynchronousfunction的完成。

您可以自己创build一些东西,或者使用asynchronous中间件,或者使用内置的function,正如Florent的回答中所指出的那样,但是我还是会在这里添加其他两个:

 var response = []; Model.find().then(function(results){ var length = Object.keys(results).length, i = 0; for(r in results){ MyService.getAnotherModel(results[r]).then(function(magic){ response.push(magic); i++; if (i == length) { // all done res.send(response, 200); } }); } }); 

或与asynchronous

 var response = []; Model.find().then(function(results){ var asyncs = []; for(r in results){ asyncs.push(function(callback) { MyService.getAnotherModel(results[r]).then(function(magic){ response.push(magic); callback(); }) }); } async.series(asyncs, function(err) { if (!err) { res.send(response, 200); } }); }); 

看看jQuery延期的对象:
http://api.jquery.com/category/deferred-object/

具体来说,当()
http://api.jquery.com/jQuery.when/