简体   繁体   中英

Promise.all for array.map with axios

What I would like to do: I have an array of book titles. eg

var bookTitleArray = ["1984", "clockwork Orange"];

For this array I would like to call an API via axios and get back detail info on each title.

What I have done so far: To do so, I have created an array.map request which calls axios which is wrapped into an async function.

The axios async function looks like following:

async function axiosWrapper (Item){
    var ItemPromise = axios.request({
            url: 'some URL',
            method: 'get',
            baseURL: 'some URL',
            headers: {
                'Authorization': 'some authorization'
            }
          })
    var axiosResult = await ItemPromise;
    return axiosResult
}

I have console.logged the axiosResult and it delivers the right data back. Hence the axios seems to work

The async with the promise.all looks as following:

async function mapWrapper(ArrayToRunThrough){

    var promiseArray = ArrayToRunThrough.map(Item => {
        axiosWrapper(Item)
    })

    var ArrayOfResults = await Promise.all(promiseArray);
    console.log(ArrayOfResults);
}

In the end I invoke the mapWrapper with the array of books I would like to search

mapWrapper(bookTitleArray)

What I experienced: Unfortunately I get back only two arrays of "undefined".

My assumption: I assume the Promise.all / await to not work as expected.

Where I need help: How can I get the actual values from the Axios API call in this setup in the "ArrayOfResults"?

You are not returning your axiosWrapper in your map . You should do:

async function mapWrapper(ArrayToRunThrough){

    var promiseArray = ArrayToRunThrough.map(Item => {
        return axiosWrapper(Item)
    })

    var ArrayOfResults = await Promise.all(promiseArray);
    console.log(ArrayOfResults);
}

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