美文网首页
async&await

async&await

作者: 弹指一挥间_e5a3 | 来源:发表于2019-04-18 17:25 被阅读0次

前提纲要:你得会promise

async的作用

  1. 能和promise结合在一起用。
  2. 能使异步函数更像同步函数。

如何用?

以掷骰子这个小demo为例(简明起见,用了中文)

function 掷骰子(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      let n = parseInt(Math.random()*6+1,10)
      resolve (n)
    },1000);
  })
}

let n = await 掷骰子() //语法错误

async function test(){
  let n = await 掷骰子();
  console.log("骰子的点数是"+n)
}
test()
// promise写法

掷骰子().then(
  x=>{
      console.log("骰子的点数是"+x)
  }
)


注:await只能放在async函数里面

获取错误结果范例

function 猜大小(猜测){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      let n = parseInt(Math.random()*6+1,10)
      if(n > 3){
        if(猜测 === "大"){
          resolve(n)
        }else{
          reject(n)
        }
      }else {
        if(猜测 === "小"){
          resolve(n)
        }else{
          reject(n)
        }
      }

    },1000);
  })
}


async function test(){
  try {
    let n = await 猜大小("大");
    console.log("你赢啦"+n)
  } catch(error){
    console.log("输光啦"+error)
  }
}
test()

//promise写法

掷骰子().then(
x=>{
  console.log("你赢啦"+x)
},
error=>{
  console.log("输光啦"+error)
}
)

其实发现async、await的写法还不如promise.then(f1,f2)来的优雅简洁,那为什么还要用async、await呢?

因为一开始说的:为了让异步代码看起来更像是同步代码。

promise.then(f1,f2)写法你会不是很明确f1,f2函数的执行顺序,但是async,await很明确,要么就执行try中的,要么就哪里出错执行catch中的。

接下来看更加复杂的写法,promise.all,也就是我们掷两个骰子。

//promise写法
Promise.all([猜大小("大"),猜大小("大")])
        .then(
          x=>{
            console.log("好嗨哦"+x)
        },
          error=>{
            console.log("输光啦"+error)
          }
        )

// async写法
async function test(){
  try {
    let n = await Promise.all([猜大小("大"),猜大小("大")]);
    console.log("你赢啦"+n)
  } catch(error){
    console.log("输光啦"+error)
  }
}
test()

可以看出async更加复杂的写法也仅仅是调用了promiseapi,所以promise会,async背一下用法也就会啦!

相关文章

网友评论

      本文标题:async&await

      本文链接:https://www.haomeiwen.com/subject/eszgwqtx.html