作者:Dmitri Pavlutin
译者:前端小智
起源:Dmitri Pavlutin

有幻想,有干货,微信搜寻 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。

当从一个异步函数的promise返回时,咱们能够应用return await promise期待 promise 解析完,也能够间接返回它 return promise

async function func1() {  const promise = asyncOperation();  return await promise;}// vsasync function func2() {  const promise = asyncOperation();  return promise;}

这两个表达式都是无效的。然而,在某些状况下,这些表达式的体现会有所不同吗?咱们往下看。

1. 雷同的行为

为了找到这两个表达式(返回 await promise vs return promise)之间的区别,咱们须要一个辅助函数 delayedDivide(n1, n2)

该函数除2个数字,并返回蕴含在promise中的除法后果:

function promisedDivision(n1, n2) {  if (n2 === 0) {    return Promise.reject(new Error('Cannot divide by 0'));  } else {    return Promise.resolve(n1 / n2);  }}

如果第二个参数(除数)是 0,该函数返回一个 reject,因为除以 0 是不可能的。

定义了辅助函数之后,咱们来跑几个例子。

上面的函数divideWithAwait()应用return await promisedDivision(6,2)表达式来返回包裹在promise中的 6 除以 2 的除法

async function divideWithAwait() {  return await promisedDivision(6, 2);}async function run() {  const result = await divideWithAwait();  console.log(result); // logs 3}run();

事例地址:https://codesandbox.io/s/with...

run()函数中,await divideWithAwait()表达式的计算结果为除法后果 3,一切正常。

如果有返回不带await关键字,后果又会怎么样呢?

async function divideWithoutAwait() {  return promisedDivision(6, 2);}async function run() {  const result = await divideWithoutAwait();  console.log(result); // logs 3}run();

事例地址:https://codesandbox.io/s/with...

即便在divideWithoutAwait() 中没有应用 await 关键字,run() 函数中的表达式awaitdivideWithoutAwait() 的后果也是正确的。

在这一步,咱们曾经看到应用return await promisereturn promise并没有什么不同。

2.不同行为

当初咱们采纳另一种办法,要使函数 promisedDivision(n1, n2)返回一个被回绝的promise,咱们将第二个参数设置为 0

因为promisedDivision(n1, 0) 会返回一个异样,咱们应用 try {... } catch (error) {...}

async function divideWithAwait() {  try {    return await promisedDivision(5, 0);  } catch (error) {    // Rejection caught    console.log(error); // logs Error('Cannot divide by 0')  }}async function run() {  const result = await divideWithAwait();}run();

事例地址:https://codesandbox.io/s/with...

如果没有 await,后果又会怎么样?

async function divideWithoutAwait() {  try {    return promisedDivision(5, 0);  } catch (error) {    // Rejection NOT caught    console.log(error);  }}async function run() {  const result = await divideWithoutAwait();}run(); // Uncaught Error: Cannot divide by 0

事例地址:https://codesandbox.io/s/with...

然而,这次,catch(error) { ... }并没有捕捉到异样。

到这,咱们就应用return await promisereturn promise之间的次要区别了。

~完,我是刷碗智,我要去 SPA 了,咱们下期见!


原文:https://dmitriplutin.com/retu...

交换

文章每周继续更新,能够微信搜寻「 大迁世界 」第一工夫浏览和催更(比博客早一到两篇哟),本文 GitHub https://github.com/qq449245884/xiaozhi 曾经收录,整顿了很多我的文档,欢送Star和欠缺,大家面试能够参照考点温习,另外关注公众号,后盾回复福利,即可看到福利,你懂的。