Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async、await #51

Open
lyyh opened this issue Mar 21, 2019 · 0 comments
Open

async、await #51

lyyh opened this issue Mar 21, 2019 · 0 comments

Comments

@lyyh
Copy link
Owner

lyyh commented Mar 21, 2019

介绍

Generator 函数的语法糖。

  • 内置执行器
  • 更好的语义
  • 更好的适用性
  • 返回值是 Promise

Async 表示函数内有异步操作、Await 表示需要等待后面的表达式的执行结果。

特性

  1. async 函数返回一个 Promise 对象
    async函数内部返回值作为then回调函数的参数。
    如果async函数内部抛出异常,则返回的promise变成reject状态,被catch回调函数接收到。

  2. async 函数返回的对象,必须要等到内部的所有 await 命令的 Promise 对象执行完,状态才会发生改变

  3. 正常情况下,await 命令后面跟的是thenable对象,如果不是也会立即被转换成 resolve 的 Promise

  4. await 实际上接收到是后面 promise 调用 then方法的 resolve 回调函数参数。

用 Promise.resolve 来模拟 async/await

async function test(){
    var res = await Math.random() * 10
    if(res>5)return true
    else return false
}


test().then(val=>console.log(val))

// 模拟
function mockTest(){
    return Promise.resolve(Math.random()*10).then(function(res){
        if(res>5)return true
        else return false
    })
}

mockTest().then(val=>console.log(val))

使用Async包裹一个function,返回 promise

async function foo(arg){
    if(arg) return true   
    else return new Error('error!')    
}
foo(false)
.then(val=>console.log(val))
.catch(val=>console.log(val))

如果不存在继发关系,则让他们同时触发

// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);

// 写法二
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;

多层调用函数同步执行

每层都要加 await

async function f(timer) {
  await new Promise((resolve,reject)=>{
    setTimeout(()=>{
      console.log(`${timer}之后`)
      resolve()
    },timer)
  })
}

async function foo () {
  try {
    await f(1000)
    console.log('done')
  }catch(e){
    console.log(e)
  }
}
foo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant