Javascript 承诺结果的数据不能使用

Javascript 承诺结果的数据不能使用,javascript,asynchronous,promise,fetch,Javascript,Asynchronous,Promise,Fetch,我想我有一些noob问题,但我无法理解为什么这段代码不能按预期工作。 问题是,我想使用我的承诺的结果(数组)来调用我需要的ID,但由于某些原因,它并没有像我期望的那个样工作。如果我调用b,那么((customerIds)=>customerIds)就在b之后,我得到了带有值的数组,但如果我在body上调用它,它就不起作用了 const a=fetch('/orders')。然后(rawOrders=>rawOrders.json()) 让b=a。然后((订单)=>{ 让CustomerList=

我想我有一些noob问题,但我无法理解为什么这段代码不能按预期工作。 问题是,我想使用我的承诺的结果(数组)来调用我需要的ID,但由于某些原因,它并没有像我期望的那个样工作。如果我调用
b,那么((customerIds)=>customerIds)
就在b之后,我得到了带有值的数组,但如果我在body上调用它,它就不起作用了

const a=fetch('/orders')。然后(rawOrders=>rawOrders.json())
让b=a。然后((订单)=>{
让CustomerList=[]
orders.forEach(元素=>{
customersList.push(element.customer)
});
返回客户列表
})
获取(“/users”{
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify({
id:b.then((customerIds)=>customerIds)
})//问题出在这里
})。然后(rawUsers=>rawUsers.json())。然后(users=>console.log('users',users));

您可以在
b中执行第二次提取,然后执行回调

比如:

尽管如此,我通常会像这样编写整个代码块

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)

ids:b。然后((customerIds)=>customerIds)
。。。因为
。然后
返回一个承诺,
ids
将是一个承诺。。。所以,在像
b这样的东西里面。然后(customerList=>{code})
你可以使用
ids:customerList
对我来说还不是很清楚,我不明白ids现在是一个承诺,但是我如何使用我的customerListok的价值,我想到了这个主意,谢谢你的帮助,我会了解更多。谢谢!
(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);
    }
})();