Day13-Async && Await

前言

虽说ES6推出了promise解决了callback hell的问题,但人总是不容易满足。

於是在ES7 有了Async && Await的出现,写起来更是直觉简单

Async

Async是宣告function的关键字

以下为宣告async function之写法

const fetchFN = async() => {
    //block
}

async function getFn () {
  //block
}

Await

顾名思义 "等待",在Async function中我们可以使用await明确的等待有资料回传,再依序执行下去。

const api = 'https://fakestoreapi.com/products'

const fetchFN = async() => {
  const data = await fetch(api)
  const result = await data.json()
  console.log(result)
}

首先宣告一个非同步函式,定义一个data变数接住fetch回传的资料,然後把data使用.json转为json档之後回传给result变数。

再来对比promise写法

function getFN () {
  fetch(api)
  .then((data) => data.json())
  .then((result) => console.log(result))
}

async function当然也可以使用.then .catch抓住错误

const api = 'https://fakestoreapi.com/sdfdsafdsfda' //wrong api

const fetchFN = async() => {
  const data = await fetch(api) //return reject
  const result = await data.json()
  console.log(result)
}
fetchFN().then(() => console.log('success'))
fetchFN().catch((err) => console.log(err)) //error

我喜欢async的写法,会比较有循序渐进的感觉!!!

/images/emoticon/emoticon07.gif


<<:  Day04常用的基本标签(HTML)

>>:  System Design: 读书心得2

<Day27> 永丰金iLeader — 查询帐务

● 这章会示范如何透过永丰iLeader查询交易帐务 接续前一章,我们这章来查询股票买卖的交易纪录 ...

Kotlin Android 第20天,从 0 到 ML - RecyclerView - GradView

前言: RecyclerView 的 ListView 完成了,但我想要用GradView怎麽辨? ...

iOS APP 开发 OC 第十一天,block 简写

tags: OC 30 day void (^myBlock1)() = ^void(){ NSLo...

WhatsApp Business 商业帐号的独特功能

WhatsApp是世界上最多人使用的即时通讯软件,每月有20亿活跃用户,用户透过WhatsApp每天...

Day 6 - TiKV架构

TiKV Server是负责保存数据资料,采key-value模式储存,且key的排列是二进制有序的...