承诺结果的数据不能使用



我想我有一些小问题,但我无法理解为什么这段代码不能按预期工作。问题是,我想使用promise的结果(数组(来调用我需要的id,但由于某种原因,它并没有像我预期的那样工作。如果我在b之后调用b.then((customerIds) => customerIds),我得到了带有值的数组,但如果我在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(

相关内容

  • 没有找到相关文章

最新更新