ThinkAndCode
ThinkAndCode

Reputation: 1657

How to wait for the async/await process untill getting the result?

I have an async / await process like below

async function getFirebaseToken() {
   firebase_token = await iid().getToken();
}

since this is an async operation, We cannot say when this process is completed. I do not want to continue to next step until i get the firebase_token. For this I have gone through this solution . But it didn't work for me.

Any suggestion on How to wait for the async/await process untill getting the result?

Upvotes: 0

Views: 116

Answers (1)

GBourke
GBourke

Reputation: 1953

the calling function will either need to be called with in async function with await, or use the .then at the "top" of the calling functions

for example, if you are fetching the token on click

const handleClick = () => {
 //async functions return a promise. Handle the end-of-line here
 getFirebaseToken()
   .then(token => { //do something with the token})
   .catch(error => {//handle the error})
}

the async function return a promise, which is handled in the onClick button. the return value will be available as "token" in the above promise handler

async function getFirebaseToken() {
   firebase_token = await iid().getToken();
    //this will be available in the .then function, as token
   return token; 
}

Upvotes: 1

Related Questions