How to get function to return value synchronously when calling a Promise?

Viewed 47

I have a function that calls an async method which returns a promise. I need the function to return the value based on the promise's resolved value. But when I try to do this, typescript throws an error saying the value is being used before being defined.

const myFunction = async (id: string): MyProductInterface {

  let isvalidProduct = false;
  let myProduct: MyProductInterface;

  await myClient.clientmethod(id)
  .then((response) =>{
    if (response == "valid"){
      isvalidProduct = true; 
    }
  })

  if(isvalidProduct){
    myProduct = //code to create MyProductInterface object with some values set to true;
  }else{
    myProduct = //code to create MyProductInterface object with some values set to false;
  }

  return myProduct;
}

clientmethod(id) method is asynchronous but I need to wait for the promise to resolve because I return myProduct which is dependent of the resolution of the promise. How can I get this to work?

1 Answers

Don't make it more complicated than necessary:

async function myFunction(id: string): Promise<MyProductInterface> {

  const response = await myClient.clientmethod(id);
//^^^^^^^^^^^^^^^^

  if (response == "valid") {
    return … //code to create object with some values set to true;
  } else {
    return … //code to create object with some values set to false;
  }
}

However, no, myFunction(…) is still asynchronous and will always return a promise, it is impossible to make it return synchronously. All the await does is to ensure that the response is checked and the result object is created after myClient.clientmethod(id) has finished.

Related