# 1.promise是什么
promise的出现是为了解决地狱回调,代码风格方便维护、容易理解,
promise的状态有哪些?
promise有三种状态, pending(初始状态), fulfilled(操作成功), rejected (操作失败) promise的状态一改变,便会凝固,不会在变
const promise = new Promise((resolve, reject) => {
console.log(1);
console.log(2);
});
promise.then(() => {
console.log(3);
});
console.log(4);
// 打印结果 124
promise.then 是微任务,它会在所有的宏任务执行完之后才会执行,同时需要promise内部的状态发生变化,因为这里内部没有发生变化,一直处于pending状态,所以不输出3。
promise的方法有哪些?
.then 两个参数成功和失败
.race 接受数组,哪个最快得到结果就返回哪个
.all 接受数组,所有的成功返回成功结果数组,如果其中有失败则返回失败的promise结果,(失败后就暂停执行)
.finally 无论成功或者失败都会走这个函数,和.then函数是同步执行的
.then抛出的异常如果有.catch会执行catch函数
async await
async await 是promise的语法糖,看着像是同步代码,其实是异步,可以用try catch try(如果抛异常)catch(则走catch里的内容)
process.nextTick
当前队列的最后执行