javascript - 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 在继续之前没有等待获取完成,这完全令人困惑。
解决方案
你getC
和getG
承诺实际上并没有等待他们的行动完成。
您需要从外部回调进入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 => {
...
});
推荐阅读
- lua - 返回更多函数的函数创建无限循环
- python - 读取 .csv 的内容并使用 python 将其写入另一个 .csv 文件
- mysql - MySQL 在两个 ISO 格式的日期之间进行选择
- c++ - 带有 libc++ 异常的 Clang
- python - Python中普通变量访问有什么用?
- mongodb - 计算 MongoDB 中每个用户的页面查看日志
- xamarin - 如何使用 SkiaSharp 测量尾随空格?
- c# - 如何在 ASP.NET Core 中结合 FromBody 和 FromForm BindingSource?
- jquery - 如何安排从 JSON 文件接收和发送的聊天对话数据?
- sql - 使用基于不同表的关系的数据创建 SQL 视图