javascript - 承诺结果数据不能使用
问题描述
我猜我有一些菜鸟问题,但我无法理解为什么这段代码不能按预期工作。问题是我想使用我的承诺(数组)的结果来调用我需要的 id,但由于某种原因它没有按我的预期工作。如果我b.then((customerIds) => customerIds)
在 b 之后调用,我会得到带有值的数组,但如果我在 body 上调用它,它就不起作用。
const a = fetch('/orders').then(rawOrders => rawOrders.json())
let b = a.then((orders) => {
let customersList = []
orders.forEach(element => {
customersList.push(element.customer)
});
return customersList
})
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
ids: b.then((customerIds) => customerIds)
}) // Here is the problem
}).then(rawUsers => rawUsers.json()).then(users => console.log('users', users));
解决方案
你可以在b.then
回调中进行第二次获取
喜欢:
const a = fetch('/orders').then(rawOrders => rawOrders.json())
let b = a.then((orders) => {
let customersList = []
orders.forEach(element => {
customersList.push(element.customer)
});
return customersList
});
b.then(customerIds =>fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
ids: customerIds
})
})).then(rawUsers => rawUsers.json()).then(users => console.log('users', users));
虽然,我通常会像这样编写整个代码块
fetch('/orders')
.then(rawOrders => rawOrders.json())
.then(orders => orders.map(({customer}) => customer))
.then(ids => fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ids})
}))
.then(rawUsers => rawUsers.json())
.then(users => console.log('users', users))
.catch(err => console.error(err));
一条长长的承诺链——最后有一个陷阱
或异步/等待
(async () => {
try {
const rawOrders = await fetch('/orders');
const orders => await rawOrders.json();
const ids = orders.map(({customer}) => customer);
const rawUsers = await fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ids})
});
const users = await rawUsers.json();
console.log('users', users);
} catch(err) {
console.error(err);
}
})();
(仅当此代码不在异步函数中时才需要异步 IIFE)
推荐阅读
- database - 获取 Mongodb 中特定页面的关注者数量
- json - Azure DevOps Pipeline Json 变量替换 - Microsoft.Hosting.Lifetime
- html - Django 和 HTML - 将 div 放置在元素内会使其出现在错误的位置
- regex - 从 Google 表格中的链接中提取带有协议和国家/地区代码的域
- java - Java 9 第三方模块«链接»,如何?,何时?-> java.lang.NoClassDefFoundError
- r - 使用字符串指定回归公式中使用的变量
- javascript - Scriptlet 不在 Gsheet App 脚本中打印 JS 和 CSS 文件
- pine-script - Pine 脚本,尝试将指标从版本 2 迁移到 4 时出现多个错误
- sparql - SPARQL:从可能的关系列表中查找连接两个实体的关系
- java - 带有 GraphQL 服务器的 Spring Boot 未启动