Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

reactjs - Javascript async/await function in async/await function


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here, I'm assuming function2 is asynchronous and performs some kind of async work. I'm simulating that async work in the code below with the delay function.

In your code, you do not call function2; the () is missing from the function call.

Also, the call is not awaited. Since function2 is async, it will begin running but execution will continue on as await is required to tell JS you want to wait until the function's returned promise is resolved before continuing.

If this is still unclear, I advise you read the MDN docs on async/await

The following is a working example:

const function2 = async () => {
  try {
    // .. do some async stuff, such as:
    const delay = ms => new Promise(res => setTimeout(res, ms))
    await delay(3000)
    
    return true;
  }
  catch {
    return false;
  }
}

const function1 = async () => {
  let isSuccess = false;
  isSuccess = await function2();
  
  return isSuccess;
}


// Test it out:
async function main(){
  console.log("calling function1...");
  console.log("function1 returned: " + await function1());
};
main();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...