0

can you call an async function with .then().catch() construct ?

const bar = require('./foofile');
let result = '';
bar.fooFunc()
.then(function(data){
  data.forEach(function(value){
     //add a new line
     result += `${value}`;
  })
})
.catch(error => console.log(error));

file : foofile.js

async function fooFunc(){
  //this returns an array
}
arve
  • 569
  • 2
  • 10
  • 27
  • 2
    What is the actual problem you've encountered when you tried this? – VLAZ Apr 28 '22 at 11:47
  • Yes, you can. `async` functions return promises. – T.J. Crowder Apr 28 '22 at 11:48
  • 1
    But note that `result` will remain blank until the promise has been fulfilled; [more here](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – T.J. Crowder Apr 28 '22 at 11:49
  • @T.J.Crowder - so how do i make sure , i get the result , either success or failure. – arve Apr 28 '22 at 11:53
  • 1
    @arve - I don't quite understand what you mean by that. If the promise is fulfilled, your fulfillment (`then`) handler will get called. If it's rejected (or an error occurs in your fulfillment handler), your rejection (`catch`) handler will get called. If you just want to know when it settles but you don't care how (fulfillment vs. rejection), use `finally`. – T.J. Crowder Apr 28 '22 at 11:55
  • 1
    @arve: *"can you call an async function with .then().catch() construct ?"* - Yes. And the code you're showing does exactly that. Is something not working in some way? – David Apr 28 '22 at 11:55
  • @David- I am calling a pdfjs library , in my fooFunc(). and inside my then clause, i am saving it to a text file. I am testing this and , it keeps saving an empty text file, and i dont' catch any errors either. so i wanted to make sure , i am calling it right – arve Apr 28 '22 at 11:58
  • @arve: The code shown isn't doing any of what you describe. *Most likely* you're just trying to use the result of the asynchronous operation before that operation has actually completed. But that's mostly a guess since the code shown never actually does anything with the result. So, yes, according to the code shown you are "calling it right". – David Apr 28 '22 at 12:01

0 Answers0