async await promise 异步 同步的 是个什么?
2021-09-26 本文已影响0人
愤怒的阿昆达
js异步编程官方介绍:
Promise 是异步编程的一种解决方案,比传统的解决方案——回调函数和事件——更合理和更强大,
ES6 规定,Promise对象是一个构造函数,用来生成Promise实例。
理解:
-
Promise是异步;
所以,如果想
异步编程,解决方案就是使用Promise
-
async和await一起用,目的是同步,同步什么呢?使所修饰的Promise对象的回调同步;
如果在使用Promise过程中想
同步则:async和await一起用,有效避免回调地狱
-
async修饰的function,返回的一定是Promise对象,即使不是也会调用Promise的构造方法构造一个。
async function fn1(){return 100;}等价写法:function fn2(){return new Promise( (resolve) => {resolve(100);});}
image.png
1、只要见到返回promise对象,且没有await的,都是异步的:
function threadSleep(time) {
console.log('1.线程休眠:'+ (time/1000) +'秒...');
return new Promise((resolve) => setTimeout(resolve, time));
}
function test(){
let promise = threadSleep(2000);
promise.then(()=>{
console.log('2.休眠后的回调');
});
console.log('3.等不等上一步 threadSleep 执行完?答:上一步是异步,不等');
return '4.test()函数返回结果';
}
test();
image.png
2、await一定在async修饰的function中使用,目的是为了达到同步:
function threadSleep(time) {
console.log('1.线程休眠:'+ (time/1000) +'秒...');
return new Promise((resolve) => setTimeout(resolve, time));
}
async function test(){
let promise = await threadSleep(2000);// await一个promise对象
promise.then(()=>{
console.log('2.休眠后的回调');
});
console.log('3.等不等上一步 threadSleep 执行完?答:等,因为 promise 异步被 await 了');
return '4.test()函数返回结果';
}
test();
image.png
报错了 呵呵。这里的promise变量得到的是undefined值,因为是同步,所以不存在后续还有回调就是简单的顺序执行。下面这样写就对了:
function threadSleep(time) {
console.log('1.线程休眠:'+ (time/1000) +'秒...');
return new Promise((resolve) => setTimeout(resolve, time));
}
async function test(){
// await一个promise对象
await threadSleep(2000);
console.log('3.等不等上一步 threadSleep 执行完?答:等,因为 promise 异步被 await 了');
return '4.test()函数返回结果';
}
test();
image.png
附:
利用 setTimeout 异步性,把其封装成返回 Promise对象后,使用时 await 即可实现 js 中的线程睡眠等待。类似 java 中的 Thread.sleep(xxx);
代码:
function threadSleep(time) {
console.log('1.线程休眠:'+ (time/1000) +'秒...');
return new Promise((resolve) => setTimeout(resolve, time));
}
使用:
async function test(){
// 业务逻辑1
console.log('业务逻辑1:', new Date());
// 线程休眠 2 秒:
await threadSleep(2000);
// 业务逻辑2
console.log('业务逻辑2:', new Date());
}
test();
image.png