Moment For Technology

Node.js knowledge system (8)- Async_await for asynchronous programming

Posted on Aug. 9, 2023, 5:12 a.m. by Jonathan Richards
Category: The back-end Tag: node.js The back-end

This is the 28th day of my participation in Gwen Challenge

  • Async fNCtion is a syntactic sugar wrapper for Promise

  • The ultimate solution to asynchronous programming - write asynchronously in a synchronous manner

    • awaitThe keyword can be "pause ⏸"async functionThe implementation of the
    • awaitThe keyword can be obtained synchronouslyPromiseExecution result of
    • try catchCan captureawaitThe error
  • A function that traverses event loops - can link code between multiple event loops ????

Async Function is a syntactic sugar wrapper for promises

const a = async function () {
  return 1;
};

const b = function () {
  return new Promise((resolve, reject) =  {
    resolve(1);
  });
};

console.log(a());
console.log(b());
Copy the code

const aa = async function () {
  throw new Error("1");
};

const bb = function () {
  return new Promise((resolve, reject) =  {
    resolve(new Error("1"));
  });
};

console.log(aa());
console.log(bb());
Copy the code

Async /await to write asynchronous code in a synchronous manner

(function () {
  const result = (async function () {
    const content = await new Promise((resolve, reject) =  {
      setTimeout(() =  {
        resolve("content-res");
      }, 500);
    });

    console.log("content", content);
    return 4; }) ();setTimeout(() =  {
    console.log("result", result);
  }, 800); }) ();Copy the code

awaitWill wait for laterPromiseWhen the result is obtained, the next line of code is executed

Try catch can catch errors in async/await asynchronous tasks

(function () {
  const result = (async function () {
    let content = null;
    try {
      content = await new Promise((resolve, reject) =  {
        setTimeout(() =  {
          reject(new Error("fail"));
        }, 500);
      });
    } catch (error) {
      console.log("error", error);
    }

    console.log("content", content);
    return 4; }) ();setTimeout(() =  {
    console.log("result", result);
  }, 800); }) ();Copy the code

Modify multiple rounds of interview code - serial

What is the first round of the interview
function interview(round) {
  return new Promise(function (resolve, reject) {
    setTimeout(() =  {
      if (Math.random()  0.2) {
        // resolve, reject Accepts only one argument
        resolve("success");
      } else {
        const error = new Error("fail"); reject({ round, error }); }},500);
  });
}

(async function () {
  try {
    await interview(1);
    await interview(2);
    await interview(3);
  } catch (error) {
    console.log(The first `${error.round}I failed in the interview);
    return;
  }
  console.log("Success in every interview! ?"); }) ();Copy the code

To realize the parallel

//
function interview(name) {
  return new Promise(function (resolve, reject) {
    setTimeout(() =  {
      if (Math.random()  0.2) {
        // resolve, reject Accepts only one argument
        resolve("success");
      } else {
        const error = new Error("fail"); reject({ name, error }); }},500);
  });
}

(async function () {
  try {
    await Promise.all([
      interview("tenxun"),
      interview("ali"),
      interview("huawei"),]); }catch (error) {
    console.log(` interview${error.name}Failed `);
    return;
  }
  console.log("Successful interview with every company! ?"); }) ();Copy the code

The last

This article is shallow, you are welcome to see the officer comments left your opinion!

Feel the harvest of the students welcome to like, pay attention to a wave!

The articles

Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.