DEV Community

ChuangWANG
ChuangWANG

Posted on

Promise & await & resolve & reject & then & catch

function resolveAfter2Seconds(x) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(x);
    }, 2000);
  });
}

async function f1() {
  await new Promise(resolve => {
    setTimeout(() => {
      console.log("test")
      // resolve(10);
    }, 2000);
  });
  console.log(10); // the line will not be execute
}

f1();

async function f2() {
  await new Promise(resolve => {
    setTimeout(() => {
      console.log("test")
      resolve(10);
    }, 2000);
  });
  console.log("the f2 line will be executed"); // the line will be executed
}

f2()

async function f3() {
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("test")
      reject(10);
    }, 2000);
  });
  console.log("the f3 line will not be executed"); // the line will not be executed, and an unhandled error occurs.
}

f3()

async function f4() {
  await new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("test")
      reject("reject content");
    }, 2000);
  }).catch((reject)=>console.log(reject));
  console.log("the f4 line will be executed"); // the line will be executed.
}

f4()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)