Home > Software engineering >  If statement not waiting for async function to execute
If statement not waiting for async function to execute

Time:01-20

I want my program to execute the code in the second else statement when reponse equals to 0.

However, it seems like it's not waiting for the function to complete and always executes what's in the true branch.

I'm not really familiar with async/await and would appreciate some guidance here.

 async function fetchInvoice(currentValue, callback) {
   let requestData = basePayload;
   requestData.body = //requestbody;
        
   let productData = await fetch(baseUrl, requestData);
   let jsonData = await productData.json();
        
   if (await jsonData.result.records.length !== 0) {
     //code
   } else {
     return false;
   }
 };
        
 if (fetchInvoice(myParameter)) {
   //code
 } else {
   //code
 }

CodePudding user response:

There are (at least) two issues...

First, myFunction never returns true. For any logical condition where you want the function to return true, add a return statement:

return true;

Otherwise, if the function doesn't return anything, its result is undefined which is falsy.

Second, you forgot to await the async function:

if (await fetchInvoice(myParameter)) {
  //code
} else {
  //code
}

Or, if this code is executing in a context which can't use await (such as top-level code in a browser) then you can follow up the Promise with .then:

fetchInvoice(myParameter).then(x => {
  if (x) {
    //code
  } else {
    //code
  }
});

As an aside, you don't need await here:

if (await jsonData.result.records.length !== 0) {

Don't just randomly sprinkle keywords around the code. await is used for a specific purpose, to await the result of a Promise. There's no Promise in this operation.

CodePudding user response:

You need to actually call myFunction and await/.then. If you just call it, it will return a Promise (because it's async) which is truthy. awaiting it will give you the actual value

if (await myFunction()) {
  // True
} else {
  // False
}
  • Related