node.jsfunctionfor-loopconvertapi

Function call inside loop gets called after the loop ends


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?


Solution

  • 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 })
      ...