【问题标题】:Promise.map not returning right orderPromise.map 没有返回正确的顺序
【发布时间】:2018-03-28 20:23:37
【问题描述】:

使用蓝鸟我该如何做以下工作。

 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 调用的响应是 "one" 、 "two" 、 "three" 然后我们会期望:

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

但是我得到了

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

我该如何解决它。我不能使用异步等待,因为 IE 不支持它。

【问题讨论】:

  • 请修正缩进、分号和大括号匹配。看起来您忘记了return,但我无法通过查看该文本来判断。
  • 另外,请注意 AngularJS 在其$q 服务中拥有自己的 Promise 实现,它应该完全有能力,而无需使用单独的 Promise 库。
  • 请注意,外部 Promise 库未与 AngularJS 框架集成。只有在 AngularJS 执行上下文中应用的操作才能受益于 AngularJS 数据绑定、异常处理、属性监视等。所以最好使用AngularJS $q Service promise library

标签: angularjs asynchronous promise bluebird


【解决方案1】:

首先,您的代码格式让人很难看清发生了什么。让我稍微清理一下并添加一些 cmets,以便您查看发生了什么。

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 链正确。

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

【讨论】:

  • 如果你要在第一个 .then 中嵌套第二个非承诺返回 api 调用,你会怎么做?你会用 $q.when 包装它吗?愿意举个例子吗?谢谢
  • 您可以在$q.resolve() 中包装任何内容以实现承诺。
  • 注意:我不认为$q.map() 函数,但是使用javascript 数组.map() 函数可以实现等效功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
相关资源
最近更新 更多