Promise 和 Async/Await的区别对比

目录
文章目录隐藏
  1. Promise
  2. Async/Await
  3. 差异

在 JavaScript 中,promises 和 async/await 是处理异步操作的两种不同方法。

Promise

Promise 是最终导致异步操作完成或失败的对象。Promise 可以处于三种状态之一:待定、已完成或已拒绝。当异步操作完成时,Promise 要么以一个值实现,要么以一个错误被拒绝。

// Using Promises
function promiseFunction() {
  return  new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Resolved");
  }, 2000);
})
}

console.log("Start");
promiseFunction()
.then((result) => {
  console.log(result);
  console.log("End");
})
.catch((error)=>{
console.log(error)
});

Output:
Start
Resolved
End

Async/Await

async/await 是 Promise 之上的语法糖。它为编写异步代码提供了一种更简洁的方法,使其更易于阅读和编写。使用 async/await,可以编写看起来与同步代码相似的异步代码,而且它在引擎盖下使用了 Promise。

在 async/await 中, async 关键字用于声明异步函数。 await 关键字用于在继续执行函数之前等待承诺的解析。 await 关键字只能在 async 函数中使用。

// Using Async/Await
async function asyncFunction() {
  try {
    console.log("Start");
    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("Resolved");
      }, 2000);
    });
    const result = await promise;
    console.log(result);
    console.log("End");
  } catch (error) {
    console.error(error);
  }
}

asyncFunction()

output:
Start
Resolved
End

差异

唯一的区别在于 promise 和 async/await 的执行上下文。

当创建 Promise 并启动异步操作时,创建 Promise 后的代码会继续同步执行。当 Promise 被解析或拒绝时,附加的回调函数会被添加到微任务队列中。微任务队列会在当前任务完成后,但在下一个任务从任务队列中处理出来之前进行处理。这意味着在创建 Promise 之后的任何代码都将在执行附加到 Promise 的回调函数之前执行。

另一方面,在使用 async/await 时, await 关键字会使 JavaScript 引擎暂停执行 async 函数,直到 Promise 解析或被拒绝。当 async 函数等待 Promise 解析时,它不会阻塞调用栈,因此可以执行任何其他同步代码。一旦 Promise 解析完毕, async 函数将继续执行,并返回 Promise 的结果。如果被拒绝,则会抛出一个错误值。

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » Promise 和 Async/Await的区别对比

发表回复