【问题标题】:Use responses from multiple promises in one function在一个函数中使用来自多个承诺的响应
【发布时间】:2017-06-23 19:26:45
【问题描述】:
var users = Api.fetchUsers()
  .then(json => dispatch(fetchIndexPageSucceed(json)));

var skills = Api.fetchSkills()
  .then(json => dispatch(fetchIndexPageSucceed(json)));

我需要创建一个使用上述两个承诺的数据的 redux 操作。我尝试使用Promise.all,但无法同时获得两个响应。

【问题讨论】:

  • 你想怎么加入json?
  • Promise.all 怎么让你失望了?
  • Promise.all 正在一一发送。我想要这些回复的集合。
  • 嘿@Jonasw 我不知道如何组合这些响应
  • @vijith mv 这些承诺会返回什么,你想要什么?

标签: javascript reactjs promise react-redux


【解决方案1】:

试试这样的。

Promise.all([Api.fetchUsers(), Api.fetchSkills()])
.then(([users, skills]) => {
       dispatch(fetchIndexPageSucceed(users))
       dispatch(fetchIndexPageSucceed(skills))
})

([users, skills]) 正在从数组中解构。

【讨论】:

    【解决方案2】:

    Promise.all 是要走的路:

    var users = Api.fetchUsers();
    var skills = Api.fetchSkills();
    Promise.all([users,skills]).then(function(values){
     return {
      users:values[0],
     skills:values[1]
     };
    }.then(function(obj){
     console.log(obj.skills);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2017-05-16
      相关资源
      最近更新 更多