等待一个http请求完成后再发送另一个?

时间:2019-01-13 13:38:57

标签: javascript axios

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

如何在启动另一个HTTP请求之前使每个HTTP请求完成,以便可以按数组中的顺序获得结果?

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

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

2 个答案:

答案 0 :(得分:1)

为了以相同的顺序获得结果,您可以简单地使用Promise.allaxios.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 => { ... });
});

或者,如果您想避免回调的麻烦,请返回promise,然后使用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();

答案 1 :(得分:0)

您想要以下类似的东西

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(...)替换pretendProm(i)

相关问题