【问题标题】:Data of promise result cannot be used承诺结果数据不能使用
【发布时间】:2021-01-15 00:14:41
【问题描述】:

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

【问题讨论】:

  • ids: b.then((customerIds) => customerIds) ... 因为.then 返回一个promise,ids 将是一个promise ... 所以,在b.then(customerList => { code code code}) 这样的内部你可以使用ids:customerlist
  • 对我来说仍然不是很清楚,我不明白现在的 ids 是一个承诺,但我该如何使用我的 customerList 值

标签: javascript asynchronous promise fetch


【解决方案1】:

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

【讨论】:

  • 好的,我明白了,感谢您的帮助,将进一步了解它。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
  • 2018-01-02
  • 1970-01-01
  • 2017-10-18
  • 2017-04-30
相关资源
最近更新 更多