首页 > 解决方案 > 承诺结果数据不能使用

问题描述

我猜我有一些菜鸟问题,但我无法理解为什么这段代码不能按预期工作。问题是我想使用我的承诺(数组)的结果来调用我需要的 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));

标签: javascriptasynchronouspromisefetch

解决方案


你可以在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)


推荐阅读