0

Please correct me if I am wrong.

As per my understanding .then() will only execute once the dependent function finishes its task. However here I could see different order of execution.

Suppose array size is 20, console.log(i) (inside axios) prints in different order like 18, 12, 11,3,15 ... so on. using .then() can't we make it synchronous?.

I know adding await keyword in front of Axios would work perfectly. But, just to make sure, is there any other way to achieve it?.

Observed Behaviour.

  1. When we execute this without await, this would work for few array items (it will be very fast).
  2. When we execute using await keyword it will take too much time.
var pdflist = ['one','two','three','four'.........'twenty']
for (let i=0; i<pdflist.length;i++)
{
            let uri = {
              method: 'GET',
              url:'https://pdffiles/'+pdflist[i]+'.pdf',
              responseType: "arraybuffer"
            };

            axios(uri).then(results => {
            console.log(i)                // prints in different order
            console.log(results)
            })
}

RAJENDRA H
  • 83
  • 10
  • 4
    No, `.then()` does not make an asynchronous operation synchronous. The operations complete when they complete. – Pointy Apr 22 '21 at 18:05
  • 2
    Those requests will run in parallel, they won't wait to move to the next loop iteration. – zero298 Apr 22 '21 at 18:05
  • 2
    I don’t have time to write an answer right now but `Promise.all` is likely what you are looking for. – t.niese Apr 22 '21 at 18:06
  • 1
    You essentially want to look at this question, even though it uses `forEach` instead of a loop. https://stackoverflow.com/q/37576685/691711 – zero298 Apr 22 '21 at 18:07
  • 1
    you can use `async` and `await` to do it in a simple and easy way. `.then()` dosent make an async operation synchronous but you can achieve this kind of behaviour with async and await. Although it internally uses `promise` to handle it. – Punith Mithra Apr 22 '21 at 19:00

1 Answers1

1

This is how you can solve the this issue with async and await.

const fn = async () => {
    var pdflist = ['one','two','three','four'.........'twenty']
    for (let i=0; i<pdflist.length;i++)
    {
        let uri = {
          method: 'GET',
          url:'https://pdffiles/'+pdflist[i]+'.pdf',
          responseType: "arraybuffer"
        };

        const result = await axios(uri)
        console.log(i)                // prints in different order
        console.log(results);
    }
}
fn()

Using Promise.all

var pdflist = ['one','two','three','four'.........'twenty']
var promises = [];
for (let i=0; i<pdflist.length;i++)
{
    let uri = {
      method: 'GET',
      url:'https://pdffiles/'+pdflist[i]+'.pdf',
      responseType: "arraybuffer"
    };

    promises.push(axios(uri))
}

Promise.all(promises).then((allResults) => {
    allResults.forEach((res, i) => {
        console.log(i)                // prints in different order
        console.log(res);
    })
})
Punith Mithra
  • 608
  • 5
  • 9