使用async和await优化异步事件

async与await的关系

从根本意义上讲:二者成双成对出现,但是当理解了 async 返回的具体是什么的时候(二者其实也可以不成对,不建议,除特殊情况下)

// 直接返回Promise对象
function test(money) {
    return new Promise(resolve => {
        setTimeout(() => resolve(`l have ${money} yuan`), 500)
    })
}

async function result() {
    const t = await test(200);
}

// 通过async返回promise对象,推荐
async function li1() {

}
async function resu() {
    const res = await li1();
}
async

async:实质最终返回的是一个promise对象,所以如下例

function test(money) {
    return new Promise(resolve => {
        setTimeout(() => resolve(`l have ${money} yuan`), 500)
    })
}

async function result() {
    const t = await test(200);
}
await

await: 实质是将异步事件,转为同步事件,为何这样说呢,因为当两个方法,第二个方法需要用到第一个方法的返回值时,加上await就能实现意想不到的结果;如下例:

function test(money) {
    return new Promise(resolve => {
        setTimeout(() => resolve(money + 1000000), 500)
    })
}

function test1(money) {
    return test(money);
}

function test2(money) {
    return test(money);
}

// 普通 promise
function result() {
    test1(100)
    .then(res1 => test2(res1))
    .then(res2 => {
        console.log(res2); // 1000200
    })
}

// async + await
async function result() {
    const res1 = await test1(100); // console 1000100
    const res2 = await test2(res1);
    console.log(res2); // console 1000200
}

惊喜吧,完全是同步的写法啊,原因是await在等待promise返回 resolve时,会‘阻塞’下面的程序执行;
文采不够,干货填补,多多交流!

发布了19 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/an_xinyu/article/details/80598806