Promise
是一个对象 ,可以获取异步操作的消息
是提供异步任务的状态管理器
Promise使用场景
需多次顺序执行异步操作时适合用Promise。
例如,如果想通过异步方法先后检测用户名和密码,需要先异步检测用户名,然后再异步检测密码的情况下就很适合用Promise。
新建一个promise对象
new Promise((resolve,reject)=>{}) //resolve和reject都是函数
Promise特点:
Promise缺点:
then:处理promise成果状态的回调函数
catch:处理promise失败状态的回调函数
finally:无论promis成功还是失败,都会执行的回调函数
promise实例生成以后,then方法分别指定resolved状态和rejected状态的回调函数。
promise返回状态为fulfilled,then则调用函数中的内容进入宏任务队列进行排队。
举例:
console.log("a");
setTimeout(() => console.log("b"));//定时器开启
let p = new Promise((resolve, reject) => {
//reject和reslove只会触发一个执行 成功或失败
resolve();
console.log("c");
})
.then(() => {
console.log("d");
})
.then(() => {
console.log("f");
});
console.log("e");
//输出a c e d f b
promise返回状态为rejected,一般不在then方法中定义rejected状态的回调函数,而使用catch方法来做错误处理。
then块通过return是不能中断的,可以通过throw来跳转至catch实现中断。
举例:
<script>
new Promise((resolve, reject) => {
console.log("in Promise");
resolve();
})
.then(() => {
throw new Error("then Error"); //抛出错误
console.log("then");
})
.then(() => {
console.log("then continue");
})
.catch((err) => {
console.log("catch error:" + err.message);
});
</script>
//输出:
//in Promise
//catch error:then Error
async
async是一个加在函数前的修饰符,被async定义的函数会默认返回一个Promise对象resolve的值。因此对async函数可以直接then,返回值就是then方法传入的函数。
await
await 也是一个修饰符,只能放在async定义的函数内。可以理解为等待。
await 修饰的如果是Promise对象:可以获取Promise中返回的内容(resolve或reject的参数),且取到值后语句才会往下执行;
如果不是Promise对象:把这个非promise的东西当做await表达式的结果。
举例:
function print(delay, message) {
//延迟时间和文本内容
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(message);
resolve();
}, delay);
});
}
async function asyncFunc() {
await print(1000, "first");
await print(2000, "second");
await print(3000, "third");
}
asyncFunc();
//一秒后输出—"first"
//两秒后输出—"secend"
//三秒后输出—"third"