async和await

async和await

async和await是ES8提出的新关键字,实际上这两个关键字是Promise和then的语法糖,它以一种更加简洁的方式来进行异步操作,使异步操作可以像普通操作那样赋值

<script>
        async function show() {
            return Promise.resolve('hello world');
        }

        async function task() {
            const showme = await show();
            console.log(showme);
        }

        task();
</script>

async

async用来定义一个异步函数,可以加在任何函数声明前面

async function show()

async函数体内的如果没有await进行阻塞时,里面的代码可以像普通函数那样同步执行

async function task() {
     console.log(1);		//1
     console.log(2);		//2
     const showme = await show();	//阻塞执行
     console.log(showme);
}

async之所以说是promise的语法糖,可以从它的返回值来看,在没有返回值的async函数中,其返回值为promise,携带的值为undefined

async function test() {
     console.log(1);
}

console.log(test());		//Promise {<fulfilled>: undefined}       

设置返回值为普通值,其返回值为promise,携带的值为返回值

async function test() {
     return 'hello'
}

console.log(test());	//Promise {<fulfilled>: 'hello'}
test().then(message => console.log(message))	//hello

设置返回值为promise,其返回值为promise

async function test() {
     return Promise.resolve('hello')
}

console.log(test());	//Promise {<pending>}
test().then(message => console.log(message));	//hello

await

await用于等待一个promise对象,用于阻塞一个promise对象,该关键字只能在async异步函数中使用

async function show() {
     return Promise.resolve('hello world');
}

async function task() {
     const showme = await show();	//hello world
}

await可以看作then的语法糖,它可以用一种更加规范的方式来执行异步函数

不过需要注意的是,在await阻塞的ssync函数中,await阻塞之前的语句能同步执行,这一点和promise很像,但是await阻塞之后的语句需要等待阻塞完成后才能执行

async function task() {
     console.log(1);		//1
     console.log(2);		//2
     const showme = await show();	//阻塞执行
     console.log(showme);
}
posted @ 2021-11-21 16:38  JSW79  阅读(116)  评论(0)    收藏  举报
隐藏目录