gpt4 book ai didi

javascript - 使用 async/await 组合并发和顺序请求

转载 作者:行者123 更新时间:2023-11-30 14:28:45 25 4
gpt4 key购买 nike

使用 async/await,我试图尽快执行三个请求。

getIndependentThingOnegetIndependentThingTwo 返回数据而不向其端点提交任何参数。但是,getDependentThing 需要 getIndependentThingTwo 返回的列表的第一个元素的 id 属性。我有点试图遵循原则,this pizza post 中概述的内容.至少在精神上。

const getIndependentThingOne = async () => {
const url = `${root}/1`
return axios.get(url)
}

const getIndependentThingTwo = async () => {
const url = `${root}/2`
return axios.get(url)
}

const getDependentThing = async ([{ id }]) => {
const url = `${root}/3/${id}`
return axios.get(url)
}

const getIndependentThingOneAndDependentThing = async () => {
const { data: listFromIndependentThingTwo } = await getIndependentThingTwo()
const { data: listFromDependentThing } = await getDependentThing(
listFromIndependentThingTwo
)
return {
listFromIndependentThingTwo,
listFromDependentThing
}
}

const getAllData = async () => {
const [
{ data: listFromIndependentThingOne },
{ listFromIndependentThingTwo, listFromDependentThing }
] = await Promise.all([
getIndependentThingOne(),
getIndependentThingOneAndDependentThing()
])
console.log('DONE')
console.log({ listFromIndependentThingOne })
console.log({ listFromIndependentThingTwo })
console.log({ listFromDependentThing })
}

getAllData()

虽然这可行,但我想知道这是否是构建这些请求的最佳方式。返回最后两个值的对象并在此处解构它们似乎有点不对劲

const [
{ data: listFromIndependentThingOne },
{ listFromIndependentThingTwo, listFromDependentThing }
]

使用 async/await 执行此类操作是否有更惯用的模式?

最佳答案

我不会编写额外的 getIndependentThingOneAndDependentThing 函数,尤其是 async/await。我宁愿选择更简单的简单 then 语法,并在 getAllData 中执行所有操作:

const getIndependentThingOne = () => axios.get(`${root}/1`);
const getIndependentThingTwo = () => axios.get(`${root}/2`);
const getDependentThing = ([{id}]) => axios.get(`${root}/3/${id}`);

const getData = ({data}) => data;

async function getAllData() {
const promiseOne = getIndependentThingOne().then(getData);
const promiseTwo = getIndependentThingTwo().then(getData);
const promiseThree = promiseTwo.then(getDependentThing).then(getData);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

const [listFromThingOne, listFromThingTwo, listFromThingThree] = await Promise.all([
promiseOne,
promiseTwo,
promiseThree,
]);
console.log('DONE')
console.log({ listFromThingOne })
console.log({ listFromThingTwo })
console.log({ listFromThingThree })
}

getAllData()

(.then(getData) 是否应该被移动到 getThing 函数中,比如 async () => (await axios.get(…)) .data,归结为偏好)

关于javascript - 使用 async/await 组合并发和顺序请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51539149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com