0

So I use this API that helps me turn a .docx file into a .pdf. I placed the code that converts the file into a function. :

function conv(){
 convertapi.convert('pdf', { File: final_path })
.then(function(result) {
  // get converted file url
  

  console.log("Converted file url: " + result.file.url);

  
  finp = path + file_name.slice(0, file_name.length - 5) + ".pdf";
  console.log(finp);

  // save to file
  return result.file.save(finp);
})
.then(function(file) {
  console.log("File saved: " + file);
  process.exit(1);
})
.catch(function(e) {
  console.log("numele si/sau extensia fisierului sunt gresite");

  process.exit(1);
});
}

The code above works only for one file at a time. I made a loop that goes through every file (.docx) in my folder and save its name into an array. I go through every item of the array and call the function :

for(var j = 0; j<=i ; j++){
  file_name = toate_nume[j];
  final_path = path + file_name;
  conv();
}

The file names are stored correctly, but when I run my project, the function is called after the loop itself ends ( is called the correct number of times for each and every file). So if I have 2 files : test1.docx and test2.docx the output shows me that the conv() is called 2 times for the test2.docx, instead of one time for each file. What should I do?

Alec
  • 73
  • 2
  • 7
  • That's expected behavior, since the conversion happens asynchronously. What's wrong with the code executing after the loop, when the conversion is done? – D. Pardal Mar 02 '21 at 12:32
  • is it possible to make it synchronously? – Alec Mar 02 '21 at 12:35

2 Answers2

0

The reason might be this: The API is slow so your program is executing the loop faster than the API the can handle the requests. So what ends up happening is that you have modified the final_path variable twice before convertapi gets called, and then it gets called twice with the same final_path. Try to modify your conv function so that it accepts a parameter, e.g. path and uses that. Then call conv with the current final_path parameter:

conv(final_path)

And:

function conv(path) {
  convertapi.convert('pdf', { File: path })
  ...
Aarni Joensuu
  • 711
  • 8
  • 19
0

So you are calling n Promise in a serial. And you want to wait for the end?

You can use Promise. all

const toate_nume = ['fileName1', 'fileName2'];
const spawn = toate_nume.map(x => {
  const final_path = path + x;
  return conv(final_path);
});
Promise.all(spawn).then(results => {
  console.log('All operation done successfully %o', results);
});

or use await:

const results = await Promise.all(spawn);

the results is an array, an entry for each call.

NOTE** I pass the path as an argument instead of a global var

Raeisi
  • 1,647
  • 1
  • 6
  • 18