【问题标题】:Waiting for one http request to be done before sending another one? [duplicate]在发送另一个 http 请求之前等待完成一个 http 请求? [复制]
【发布时间】:2019-01-15 16:23:26
【问题描述】:

这一切都有效,除了每次我以不同的顺序得到结果。 例如。 2.name, 4.name, 1.name, 3.name, 5.name

我怎样才能让每个 http req 在开始另一个之前完成,这样我才能像数组一样按顺序获得结果?

const array = [ '1', '2', '3', '4', '5' ]

array.forEach(el=>{
  axios.get(`/item/${el}`)
     .then(res=>{
         console.log(res.data.name)
   }
})  

【问题讨论】:

  • 您可以创建变量以保存为数组。示例 const dataName =[...包含 res.data.names]。之后,循环组合数字和名称
  • 您可以在循环中使用 await,前提是您处于异步函数中,例如在 forEach 中,const res = await axios.get(...); console.log(res);

标签: javascript axios


【解决方案1】:

为了以相同的顺序获得结果,您可以简单地使用Promise.all,或axios.all,但这将并行执行所有请求:

const array = [ '1', '2', '3', '4', '5' ];

axios.all(array.map(el => () => axios.get(`/item/${el}`))).then(data => console.log(data));

但是,如果您需要按顺序执行它们,那么按顺序执行,因为可能在第二个请求中您需要访问第一个请求的响应,您必须将每个下一个请求链接到前一个的 then

const array = [ '1', '2', '3', '4', '5' ];

const requests = array.map(el => () => axios.get(`/item/${el}`));
requests[0]().then(data1 => {
  requests[1]().then(data2 => { ... });
});

或者,如果您想避免地狱般的回调返回承诺,然后将 then 块解开:

const array = [ '1', '2', '3', '4', '5' ];

const requests = array.map(el => () => axios.get(`/item/${el}`));
requests[0]()
  .then(data1 => requests[1]())
  .then(data2 => { ... });

或者你可以使用async/await:

const array = ['1', '2', '3', '4', '5'];
const requests = array.map(el => () => axios.get(`/item/${el}`));

async function performRequests() {
  const res1 = await requests[0]();
  const res2 = await requests[1]();
}

performRequests();

【讨论】:

  • 即使是第二个版本也不按顺序执行请求。
  • 哦,是的,你是对的,我忘了把它们包装在额外的函数中,会更新
  • 必须有比requests[1] {...} 更优雅的方式来解开这个问题……
  • 是的,如果你想避免回调的地狱,就等待异步
  • 在您的情况下,使用Promise.allaxios.all,您只需要保留响应的顺序,而不是按顺序执行它们。是否有意义?关注我发布的第一个 sn-p
【解决方案2】:

你想要类似下面的东西

const arr = [1, 2, 3, 4];

function pretendProm(i) {
    return new Promise((resolve, reject) => {
        resolve(arr[i]);
    });
}

arr.forEach(async (res, i) => {
    const x = await pretendProm(i);
    console.log(x);
});

用axios.get(...)替换prettyProm(i)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 2020-03-04
    相关资源
    最近更新 更多