[ JS个人笔记 ] Async / Await—DAY10

特点

  • Async Await 为 Promise 延伸出的特性,是 Promise 的语法糖
  • 函式本体是属於非同步,但内部以 “同步的方式运行非同步” 程序码
  • 更加简洁处理非同步事件,提高程序码可读性
  • 使用 try...catch 管理流程,将非同步事件置入於 try 流程内,当遇到错误时则在 catch 区块内接取错误讯息

各情况范例

与 Promise 搭配执行

let event = (num) => Math.floor(Math.random() *num)>2 ? true : false
let timer = (num) => Math.floor(Math.random() * num)*1000


let condition = function(something,timer,num) {
  return new Promise((resolve,reject)=>{
    setTimeout(function(){
      if(something) {
          resolve('第'+ num +".成功了花了"+timer+'秒');
      } else {
          reject('第'+ num +'次失败QQ');
      }
    },timer)
  })
}

//----------------------------只有一个非同步事件的情况----------------------------------

async function example() {
    try{
      const res1 = await condition(event(5),timer(5),1)
      console.log('event1:',res1)
    }
    catch(err){
      console.log('失败:',err)
    }
}

//---------若是两个事件以上,只要其中一个出现错误,即进入catch的阶段,并不在继续往下执行-----------

async function example() {
    try{
      const res1 = await condition(event(5),timer(5),1)
      console.log('event1:',res1)
      const res2 = await condition(event(5),timer(5),2)
      console.log('event2:',res2)
      const res3 = await condition(event(5),timer(5),3)
      console.log('event3:',res3)
    }
    catch(err){
      console.log('失败:',err)
    }
}

/*----------与 Promise.all() 搭配,在全部完成後才进行下一步,若事件都成功,则印出阵列回复,若其中rejected,.catch立即回传第一个完成的失败回复-----------*/
            
//-----与 Promise.race() 搭配,其中一事件先完成(不论成功与否),即进入对应的try...catch----------

async function example() {
    try{
      const res = await Promise.all([condition(event(5),timer(5),1),condition(event(5),timer(5),2),condition(event(5),timer(5),3),condition(event(5),timer(5),4)])
      console.log(res)
    }
    catch(err){
      console.log('失败:',err)
    }
}

//----------------------------------------------------------------------------------
example()

<<:  popcat 如何使用 python 搭配 selenium 在浏览器上自动点击

>>:  如何让 IIS 底下的 PHP 显示错误内容 (500 Error)

Day04 - 纯 Html - 复杂型别 collection

Case01 Controller [HttpPost] public IActionResult ...

语法糖小测验: Scope functions & Extension function

最近补课的模式有了改变,大部分时间都是诗忆读着讲义,遇到问题或是想要学得更深入的时候再和唯心讨论。 ...

30-26 之 DDD 战略设计 2 - 实作方法之 Event Storm

事件风暴 Event Storm 事件风暴 : 理解、访谈需求 目的 : 将商业流程视觉化,找出核心...

爬虫怎麽爬 从零开始的爬虫自学 DAY25 python网路爬虫开爬6-资料储存

前言 各位早安,书接上回我们将程序码改得更方便阅读,还加上抓取连结的功能,今天我们要来把这些抓到的资...

JavaScript学习日记 : Day26 - 重做原生方法 -- Array

算是检验自己对JavaScript理解一个很好的方法: 范例 : const cat1 = { na...