Promise.map不返回正确的订单



使用bluebird我该怎么做以下工作。

 groupCast = [Promise.resolve("name1"), Promise.resolve("name2"),Promise.resolve("name3")]
    Promise.map( groupCast , function (group){
        Promise.resolve($http.get("/getdata" , params:{group:group}))
               .then(function(response){ console.log(group," done")return response}))
        return response
        })
              .then(function(resp){console.log(resp)})

如果每个组的HTTP调用响应是"一个","两个","三"然后,我们希望有:

"name1 done";
"name2 done";
"name3 done";
[ "one" , "two" ,"three" ]

但是我得到

 [ "one" , "two" ,"three" ]
    "name1 done";
    "name2 done";
    "name3 done";

我该如何修复。我不能使用异步并等待,因为IE不支持。

首先,您的代码格式使您很难看到正在发生的事情。让我清理一点并添加一些评论,以便您看到发生的事情。

Promise.map(groupCast, function(group) {
  //the following kicks off a new promise, which is not chained to the current one
  Promise.resolve($http.get("/getdata", { params: { group: group } })).then(
    function(response) {
      console.log(group, " done");
      //you're returning response below, but it's not going anywhere!
      return response;
    }
  );
  //The current promise resolves right away, not waiting for the $http call.
  //Also, you're returning an undefined value here.
  return response;
}).then(function(resp) {
  //the prior promise resolves with undefined.
  console.log(resp);
});

现在让我们修复它,以便正确的链条正确。

Promise.map(groupCast, function(group) {
  // $http.get returns a promise already. No need to wrap it in one.
  // Also, let's go ahead and return the chained promise so the `map` function can wait for it.
  return $http.get("/getdata", { params: { group: group } })
    .then(function(response) {
        console.log(group, " done");
        return response;
      });
}).then(function(resp) {
  //the prior promise should now resolve as expected.
  console.log(resp);
});

最新更新