Async/Await 具有易于理解的示例。

2025-05-25

Async/Await 具有易于理解的示例。

我们首先来了解一下Async关键字。

将此关键字放在返回承诺或执行异步任务的函数之前。



const foo = async () => {
  return 'done';
}

foo().then((res) => console.log(res));

// done


Enter fullscreen mode Exit fullscreen mode

如果您认为您的函数将异步运行(从 API 获取数据),那么请在该函数之前使用 async 关键字。

现在有另一个关键字Await,它仅在异步函数内有效。

(有一个顶级 await 的概念,其中 await 关键字可以在异步函数之外使用。)

Await 关键字的简单含义是让 JavaScript 等待直到任务完成。



const asyncTask =  () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('done');
    }, 1000);
  });
}

const foo = async () => {
  const res = await asyncTask();
  console.log(res);
}

console.log('Before Foo Call');
foo();
console.log('After Foo Call');


Enter fullscreen mode Exit fullscreen mode

在上面的例子中,我创建了一个虚拟函数,它需要一秒钟才能返回其结果。

还有另一个函数 foo 调用 asyncTask(带有 await 关键字)并打印结果。

我放了两个日志,一个是在调用 foo 之前,另一个是在调用 foo 之后。

你觉得输出会是什么?🤔

您可能知道,每当 JavaScript 遇到 await 关键字时,它都会停止当前函数的执行并将其放入回调队列并开始执行下一个语句,即第二个控制台日志。

这是上述代码的输出。



Before Foo Call
After Foo Call
done


Enter fullscreen mode Exit fullscreen mode
使用 async/await 时处理错误

在上面的例子中,我们的承诺正常解决,并且我们在控制台上打印结果。

但如果被拒绝,它将引发错误,因此我们应该在处理承诺时处理错误。

使用 try/catch 块。



const asyncTask =  () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject('Something not working!');
    }, 1000);
  });
}

const foo = async () => {
  try {
    const res = await asyncTask();
    console.log(res);
  } catch (err) {
    console.log(err);
  }
  console.log('After calling AsyncTask');
}

foo();


Enter fullscreen mode Exit fullscreen mode

现在,如果我们的 asyncTask 函数抛出错误,控制将进入 catch 块并简单地打印错误消息,然后它将开始执行下一个语句。

输出



Something not working!
After calling AsyncTask


Enter fullscreen mode Exit fullscreen mode

很干净。不是吗?

现在,尝试在下一个项目中使用 async/await 而不是 then/catch。

如果您喜欢这篇文章,请点赞、分享并标记🔖这篇文章!

🏃‍♂️ 你可以关注我 👇

🕊 推特:https://twitter.com/nehal_mahida

👨‍💻 Github:https://github.com/NehalMahida

支持🤗

如果您喜欢我的文章,请考虑喝杯咖啡支持我。☕

文章来源:https://dev.to/nehal_mahida/asyncawait-with-easy-to-understand-examples-2221
PREV
如何不更新 React 中的状态!!
NEXT
如何让页脚固定在网页底部?问题解决方案