好玩的.async

版权声明:个人笔记,不喜勿喷 https://blog.csdn.net/qq_39571197/article/details/88996699

## 如果没有await,asycn function其实是同步的!

    // 同步
    let count = 0;
    async function fn(index = 0) {
        count++;
        if (index === 5) {
            return Date.now();
        }
        // await new Promise(resolve => {
        //     setTimeout(resolve, 1000);
        // });
        return fn(++index);
    }
    fn().then(function () {
        console.log(count);
    });
    console.log(count); // 6
    // 异步
    let count = 0;
    async function fn(index = 0) {
        count++;
        if (index === 5) {
            return Date.now();
        }
        await new Promise(resolve => {
            setTimeout(resolve, 1000);
        });
        return fn(++index);
    }
    fn().then(function () {
        console.log(count);
    });
    console.log(count); // 1

## 一旦遇到await,那么后面就是异步了 

- 如果await一个promise会更晚执行

async function async1 (){
    console.log('async1-开始');
    await genPromise(); // 对比async2,这里是异步的
    console.log('async1-结束');
}

async function async2 (){
    console.log('async2-开始');
    await 1; // 即使不是promise
    console.log('async2-结束');
}

async function genPromise (){
    await console.log('this is a promise');
}

async1();
console.log('run async1');
async2();
console.log('run async2');

 

没有更多推荐了,返回首页