0

I am new to NodeJs. I want to push elements in files array in order of url. But i am getting random order . Below is the code for same. Can anyone suggest what i am doing wrong here.

const mergePdf =async  (urlArray, files) => {
  for (let i = 0; i < urlArray.length; i++) {
    try {
      const pdfBytes = await fetch(urlArray[i]).then((res) => {
        return res.arrayBuffer();
      });
      let bytes = new Uint8Array(pdfBytes);
      files[i]=bytes;
    } catch (err) {
      console.log(err);
    }
  }
}
  • 1
    Your code *does* fill the `files` array in the same order that the `urlArray` is traversed. Nothing is random here. Can you please show us how you call this function, and what result you are getting, and what result you would have expected? – Bergi Jul 27 '21 at 12:44
  • 1
    There is no reason why the code above fills the array in random order. Are you sure that `urlArray` is in the order you expected before calling `mergePdf`? If the order you got back appears random to you then my debugging instinct tells me that `urlArray` is already in a "random" order before you called `mergePdf` – slebetman Jul 27 '21 at 13:53
  • 1
    ... or you have simplified your code too far and accidentally fixed your "random" bug in your Stackoverflow post while your real code still has race condition issues. – slebetman Jul 27 '21 at 13:54

1 Answers1

-1

write seprate function of your api call in promises like

const other_func = (url) => {
  return new Promise(async (resolve) => {//updated line
     try {
       const pdfBytes = await fetch(url).then((res) => {
       let bytes = new Uint8Array(pdfBytes);
       resolve(bytes);// return value pass in resolve method [Updated]
     });
     
    } catch (err) {
     console.log(err);
    }
 })
}

and in your original function call this function using await like

const mergePdf =async  (urlArray, files) => {
 for (let i = 0; i < urlArray.length; i++) {
 files[i] = await other_func(urlArray[i])
 }}
Ali Faiz
  • 212
  • 2
  • 9
  • Executing the first snippet from your answer gives "*Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules*" – Bergi Jul 27 '21 at 13:27
  • And even if you fix that, `pdfBytes` will be `undefined` instead of an array buffer. And even if you fix that, `files` and `i` are not defined in `other_func`. And even if you fix that, the code works just the same as the OP's original code. This approach does not solve whatever problem the OP is having. – Bergi Jul 27 '21 at 13:29
  • I have update the answer please try this one – Ali Faiz Jul 27 '21 at 13:45
  • One should [never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572) - now the loop hangs once there is an error because the `new Promise` doesn't get settled. And it still doesn't solve the OP's problem. – Bergi Jul 27 '21 at 13:55