简体   繁体   中英

Javascript - async await not wait until function is done?

I was learning javascript with async and await and tried some example on my own, but it seems when calling the async function (func1) from another function (func2), func2 does not wait for func1 to complete its process and it jumps over and continue executing...is there something wrong with my code or should I also turn func2 into async and call func1 with await? If so, does that mean all functions that will involve an async-await method will need to become async as well? here is my original code

// func1
const func1 = async() => {
   try {
     await putCallToServer(...);
     return 1;     // it returns as a promise
   } catch(ex) {
     return 2;
   }
}

// func2
const func2 = () => {
   let result = 0;
   result = func1(); // should I turn it into await func1()??
   console.log(result);  // log contains '0' instead of '1' or '2'
   return result;    // return as Promise but value inside is 0
}

And what if I have a func3 which would call func2, should I turn func3 into async-await as well?

As was stated in the comments, both functions must be async in order to use await. This can be seen below in the code snippet. (since i do not wish to call an actual server in an example, I am throwing in putCallToServer(). This is returning the result of 2.

I also changed result to be a let variable since you were trying to mut a const which is not allowed.

 async function putCallToServer() { throw "too lazy to make a real error" } // func1 const func1 = async() => { try { await putCallToServer(); return 1; // it returns as a promise } catch(ex) { return 2; } } // func2 const func2 = async() => { let result = 0; result = await func1(); // should I turn it into await func1()?? console.log(result); // log contains '0' instead of '1' or '2' return result; // return as Promise but value inside is 0 } func2()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM