美文网首页
走过路过, async + await 了解一下

走过路过, async + await 了解一下

作者: kup | 来源:发表于2018-11-14 16:49 被阅读0次

async + await 是generator的语法糖,generator已经不直接用啦,所以你需要了解的,就是async + await !
(async + await = generator + co ,co库,不了解的可以去github看看了解下~ 几行源码)

async 就是个promise, async函数可以直接.then((data)=>{ })

起步:

1. await必须结合async才能使用;

2. await后面可以跟任何数据,也可以跟同步方法或异步方法;

例子1:

async function fn(){
    console.log(0);
    await 1;
    console.log(1);
    await 2;
    console.log(2);
    await 3;
    console.log(3);
    return 4
}
fn().then((data) => {
    console.log('data', data)
})
// 打印:
// 0
// 1
// 2
// 3
// data 4

进阶:

1. await后面跟着setTimeout等非promise写的异步方法,那么async后面的then函数(若then函数里面是同步的), 则会先于await里面的异步方法执行,且async函数中,await后面非promise写的异步方法,如果是接口这种异步,则返回的时间不定,异步流仍然不好控制,看例子2就会发现,awiat函数不是按照书写顺序执行的。(强调!因为下面用了promise会发现另一片天地!)

例子2:

async function fn(){
    console.log(0);
    await setTimeout(() => {console.log(200)}, 200);
    console.log(1);
    await setTimeout(() => {console.log(100)}, 100);
    console.log(2);
    await setTimeout(() => {console.log(50)}, 50);
    console.log(3);
    return 'done'
}
fn().then((data) => {
    console.log('data', data)
})
// 打印:
// 0
// 1
// 2
// 3
// data done
// 50
// 100
// 200

例子3: 在await 后面用了promise,会发现,异步流完全可控了!!!

async function fn(){
    console.log(0);
    let a = await new Promise((resolve) => {
        setTimeout(() => {resolve(200)}, 200)
    })
    console.log(1);
    console.log('a', a);
    let b = await new Promise((resolve, reject) => {
        setTimeout(() => {resolve(a + 1)}, 100)
    })
    console.log(2);
    console.log('b', b);
    let c = await new Promise((resolve, reject) => {
        setTimeout(() => {resolve(b + 1)}, 50)
    })
    console.log(3);
    console.log('c', c);
    return c
}
fn().then((data) => {
    console.log('data', data)
})
// 打印:
// 0
// 1
// a 200
// 2
// b 201
// 3
// c 202
// data 202

总结:
async + await 是为了让书写的异步流代码能够像同步代码一样,方便控制而产生的。await只有放在async函数里面才能使用,并且只有await后面跟着promise,才能够真正起到控制异步流步骤的效果。

相关文章

  • 走过路过, async + await 了解一下

    async + await 是generator的语法糖,generator已经不直接用啦,所以你需要了解的,就是...

  • async/await的深究

    我们都知道async/await是Generator函数的语法糖,为了更加深刻的了解async/await的原理,...

  • es6--async和await

    async 和 await被称为js异步的最终解决方案,那么我们来了解下:async:异步方法, await:等待...

  • async和await

    浅谈Async/Await用 async/await 来处理异步 async和await async:声明一个异步...

  • JS异步编程(5)-async/await

    async/await 是什么 了解和使用 async 之前,需要提前了解以下部分: Event loop Pro...

  • ES8(一) —— async&await

    目录 async和普通函数的区别 await async/await处理多回调异步 async和await必须配合...

  • async

    async/await特点 async/await更加语义化,async是“异步”的简写,async functi...

  • async&await解读

    一、讲讲Promise 在讲async和await之前,我们先来了解一下Promise. Promise的语法: ...

  • ES6中的好东西

    1 Await/Async 前端的回调时代我没有赶上,我赶上的是await/async时代。await和async...

  • Vue接口调用方式(三)async/await用法

    async/await用法 1. async/await的基本用法 async/await是ES7引入的新语法,可...

网友评论

      本文标题:走过路过, async + await 了解一下

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