简体   繁体   中英

Trying to loop axios requests and push it asynchronously

async function getData() {
  let getProject =
    await axios.get('url', {
      auth: {
        username: 'username',
        password: 'pw'
      }
    })

  let projects = await getProject.data.value;
  let arr = []

  projects.map(project => {
    let item = axios.get(`url`, {
      auth: {
        username: 'username',
        password: 'pw'
      }
    })

    arr.push(item)
    console.log('arr', arr)
  })

  let result = await axios.all(arr)

  console.log('pr', result)

  return arr;
}

In the getProject I get the object of the projects by calling the API. Then I try to loop through these fetched objects and use unique url for each project to call another API in projects.map .

console.log('arr', arr) gives me the array of Promises, and some of them are failed requests and some of them are successful. This is intended because some projects might not have the valid API. But I will want an array with successful Promises.

This doesn't even reach the line console.log('pr' result) and I am not sure why.

Am I doing it right?

Try revising your code so that arr is an array of functions that return promises for axio requests (rather than arr being an array of actual axios request promises, as you are currently doing):

let projects = await getProject.data.value;

// Map all project items to functions that return promises
let arr = projects.map(project => {

    // Return a function that returns a promise
    return function() {     

        // Returns a promise for GET request
        return axios.get(`url`, {
            auth: {
                username: 'username',
                password: 'pw'
            }
            })
    } 
})

// Axios.all will concurrently perform all GET requests 
// in arr (ie the mapping of projects to functions that
// return promises from axios.get )
let result = await axios.all(arr)

// Should print results from axio.get (if all requests successful)
console.log('pr', result)

This is a subtlty with the way methods like axios.all typically work and is similar to the native Promise.all method. For more information see the example just above "axios API" in the axios docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM