首页 > 解决方案 > Promise.all 在移动到 .then 之前不等待承诺完成

问题描述

我正在尝试在 reactjs 中执行两个获取,然后处理结果以进行显示。

我已经将我的两个提取都设置为要解决的承诺。但是,当我做 promise.all 时,它会移动到 .then 在提取完成之前。这是下面的代码。

 const getC = fetch(api/getContacts, {
        method: 'GET',
        headers: {
           'Authorization': JSON.stringify(this.props.getLogin()),
           'Accept': 'application/json',
           'Content-Type': 'application/json',
        }
     })
     .then((res) => {
        console.log(res.status);
        res.json()
        .then(json => {
           json = json.sort(this.sortByProperty('contact_id'));
           console.log(json)
           this.setState({
              contactsLoading: false,
              contacts: json
           });
        })
     });
 const getG = fetch(api/getContacts, {
        method: 'POST',
        headers: {
           'Authorization': JSON.stringify(this.props.getLogin()),
           'Accept': 'application/json',
           'Content-Type': 'application/json'
        },
        body: JSON.stringify({group_id: this.props.group_id
        })
     })
     .then((res) => {
        res.json()
        .then(json => {
           console.log(json);
           var members = json.members.sort(this.sortByProperty('contact_id'));
           console.log(members);
           this.setState({
              name: json.name,
              memberIds: members,
           });
        })
     });
Promise.all([getG, getC])
     .then(() => {
        console.log(this.state.contacts);
        console.log(this.state.memberIds);
     });

预期的输出是:
[Array with items] (from getG)
[Array with items] (from getC)
[same array as get C] (in the .then)
[same array as get G]

但相反我得到:
[空数组]
[空数组](来自.then)

[来自 getG
的数组] [来自 getC 的数组]

所以我试图弄清楚为什么 Promise.all 在继续之前没有等待获取完成,这完全令人困惑。

标签: javascriptnode.jsreactjs

解决方案


getCgetG承诺实际上并没有等待他们的行动完成。

您需要从外部回调进入return内部承诺链,以使外部承诺等待该链。res.json().then(...)then()

一旦你这样做了,你还应该向上移动内部then()回调以减少嵌套:

 const getC = fetch(api/getContacts, {
        method: 'GET',
        headers: {
           'Authorization': JSON.stringify(this.props.getLogin()),
           'Accept': 'application/json',
           'Content-Type': 'application/json',
        }
     })
     .then((res) => {
        console.log(res.status);
        return res.json()
     })
     .then(json => {
        ...
     });

推荐阅读