百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> 懂得JavaScript之Async/Await的新语法
分享文章到:

懂得JavaScript之Async/Await的新语法

发布时间:09/01 来源:未知 浏览: 关键词:

受到Zeit团队博文的启示,我们的PayPal团队不久此前将效劳器端数据库迁移到了Async/Await上。我想要和你们分享一下我的经历。

第一我们先来理解两个术语:

  • Async函数
  • Await 关键词

你们总是将Async和Await放在一起说,但是你需要知道的是,它们是两个不一样的东西。关于Async函数和Await关键词,你需要理解的是,他们从某种程度上来说当然是有必然关联的,但是在没有Await的状况下,Async函数仍然可以使用。

相关学习引荐:javascript视频教程

函数会返回一个Promise

当你用async关键词创立一个函数的时候,这个函数永久都会返回一个Promise。当你在async函数内部停止返回的时候,它会用一个Promise包裹你的值。

 // here is an async function
 async function getNumber() {

  return 4 // actually returns a Promise
  }
  // the same function using promises
  function getNumber() {

     return Promise.resolve(4)

}

Async函数和它的基于Promise的Equivalent

除了将你的return转换为Promise之外,async函数还有一个特殊之处,那就是它是独一一个让你使用await关键词的地方。

Await让你可以暂停async函数的施行,直到它受到了一个promise的结果。这让你可以写出依照施行次序显示的async代码。

 // async function to show user data
 async function displayUserData() {

    let me = await fetch('/users/me')

    console.log(me)

}// promise-based equivalent
function displayUserData() {

    return fetch('/users/me').then(function(me) {

        console.log(me)

    })

})

Await同意你在不需要callback的状况下写异步代码。这样做的好处是让你的代码可读性更高。并且await可以与任何promise兼容,而不仅仅是用async函数所创立的promise。

在Async函数中处置错误

由于async函数也是一个Promise,当你在代码中放入一个async函数的时候,它会被接收,然后作为rejected Promise被返回。

 // basic error handling with async functions
 async function getData(param) {

   if (isBad(param)) {     
    throw new Error("this is a bad param")

   }   
   // ...
   }
   // basic promise-based error handling example
   function getData(param) {

   if (isBad(param)) {      
   return Promise.reject(new Error("this is a bad param"))

   }  
    // ...
    }

当你使用await调取Promise的时候,你可以用try/catch将其包裹,或是你需要在返回的Promise中增加一个catch handler。

 // rely on try/catch around the awaited Promise

async function doSomething() {   
 try {       
  let data = await getData()

    } catch (err) {       
     console.error(err)

    }

}
// add a catch handlerfunction doSomething() {    
return getData().catch(err => {      
  console.error(err)

    })

}

整合

利用好promise的错误处置属性,乃至async函数的简约语法,能够给你带来一些强大的能力。

鄙人面这个简便的例子中,你会看到我是怎样利用async函数内在的错误处置能力的,它让我简化了Express利用中的错误处置流程。

 // catch any errors in the promise and either forward them to next(err) or ignore them
 const catchErrors = fn => (req, res, next) => fn(req, res, next).catch(next)
 const ignoreErrors = fn => (req, res, next) => fn(req, res, next).catch(() => next())
 // wrap my routes in those helpers functions to get error handling
 app.get('/sendMoney/:amount', catchErrors(sendMoney))
 // use our ignoreErrors helper to ignore any errors in the logging middleware
 app.get('/doSomethingElse', ignoreErrors(logSomething), doSomethingElse)
 // controller method can throw errors knowing router will pick it up
 export async function sendMoney(req, res, next) {  
 if (!req.param.amount) {     
 throw new Error('You need to provide an amount!')  

  }  await Money.sendPayment(amount) // no try/catch needed

  res.send(`You just sent ${amount}`)}

// basic async logging middleware
export async function logSomething(req, res, next) {

    // ...    
    throw new Error('Something went wrong with your logging')

    // ...

}

此前,我们不断都在用next(err)来处置错误。然而,有了async/await,我们可以将错误放在代码中的任何位置,然后router会将这些错误throw到Express供给的next函数中,这样就极大的简化了错误处置流程。

我用了几个小时的时间对数据库停止了迁移。要想使用这个方式,你独一需要的,就是对Promise的深刻懂得,乃至学会怎样设定babel。

以上就是懂得JavaScript之Async/Await的新语法的具体内容,更多请关注百分百源码网其它相关文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有151人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板