0

I have an api function that converts an image file to a src url. And this one works well.

const requestImageUrl = (data) => {
    return axios.post(baseUrl + `/image`, data, {
        headers: {
            "Content-Type": "multipart/form-data",
        },
    });
};

I want to convert all images to urls and store them in a array.

So I made a code like down below. But it didn't work really well.

convertToUrl(images) {
    let imageUrls = []
    for (let i=0; i<images.length; i++) {
        const formData = new FormData()
        formData.append('file', images[i])
        PostingApi.requestImageUrl(formData).then(res => {
            imageUrls.push(res.data.data.image)
        })
    }
    return imageUrls
},

So I changed code like this using async and await. And it worked well.

async convertToUrl(images) {
    let imageUrls = []
    for (let i=0; i<images.length; i++) {
        const formData = new FormData()
        formData.append('file', images[i])
        const res = await PostingApi.requestImageUrl(formData)
        imageUrls.push(res.data.data.image)
    }
    return imageUrls
},

Both returned same values, array which has length of 2. But they were slightly different as you can see in the picture down below. When I open up the arrays in console, they had same things, but when they are enclosed, it wasn't same. Could you tell me why they return diffrent values?

[First one is the one that didn't use async, Second one is the one used async][1]


  [1]: https://i.stack.imgur.com/fMhdx.png
B777ICN
  • 1
  • 1
  • When closed they show different results because the first one didn't actually contain any elements at the time it was logged. When opened, the array is being reevaluated and by that time the async operation has finished and the array has elements. – Ivar Aug 12 '21 at 06:20
  • `requestImageUrl` is an async process. In the first example you're trying to log an array of items that hasn't been fully processed. In the second you've used `await` to ensure that the data _is_ available. [Browsers handle console logs differently.](https://stackoverflow.com/questions/23392111/console-log-async-or-sync) – Andy Aug 12 '21 at 06:20
  • Also note that your your `async` approach will wait for each request to finish before starting the other one. You might be able to [run them all in parallel](https://stackoverflow.com/a/37576787) to save some time. – Ivar Aug 12 '21 at 06:21

0 Answers0