6

这就是我想做的

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);

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

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

4

3 回答 3

6

由于 waterline 使用Q,您可以使用该allSettled方法。您可以在Q文档
中找到更多详细信息

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);
  });
});
于 2013-12-20T15:06:11.930 回答
3

你根本做不到,你必须等待异步函数完成。

您可以自己创建一些东西,或者使用异步中间件,或者使用内置功能,如 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);
          }
      });     
   }
});

或异步

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);
       }
   });
});
于 2013-12-20T15:11:19.437 回答
-3

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

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

于 2013-12-20T15:05:27.373 回答