Promise
Promise有三种状态: pending(挂起) fulfilled(成功) rejected(失败)
一般用法
function asyncReadFile() {
return new Promise((xxx, yyy) => {
if (true) {
xxx();
} else {
yyy();
}
})
}
asyncReadFile()
.then(() => {
})
.catch(() => {
})
最好只用catch去捕获异常。
发生错误后,后面的then会继续执行。
Promise.resolve()
.then((res) => {
console.log(res);
},err => { // 最好不要在这里捕获异常,这里捕获后,最后的catch会抓不到
console.log('err');
})
.then(() => { // 这里任然会继续执行
console.log('second');
})
.catch(() => {
console.log('catch'); // 这里不会执行
});
下一个then不会等上一个then执行完
Promise
.resolve(1)
.then((res) => {
console.log(res);
})
.then(() => {
setTimeout(() => {
console.log('second');
})
})
.then(() => {
console.log('third');
})
output:
1
third
second
必须先执行第二个then完再执行第三个then
Promise
.resolve(1)
.then((res) => {
console.log(res);
})
.then(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
console.log('second');
}, 5000)
})
})
.then(() => {
console.log('third');
});
promise.all 注意不需要new,
Promise
.all([Promise.resolve({data: 'bi'})/*requestGet(API.getDefaultGroup)*/, requestGet(API.getAllGroup)])
.then((res) => {
res = res || [];
const defaultData = res[0] || {};
const AllData = res[1] || {};
this.groupName = defaultData.data || [];
this.groupList = AllData.data || [];
})
曾经遇到的一个面试题:实现5秒超时
const p = Promise.race([ // 注意这里不要用 new Promise
new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1);
}, 2000)
}),
new Promise((resolve, reject) => {
setTimeout(() => {
reject(0);
}, 5000)
})
]);
p.then((res) => {
console.log(res);
}).catch((err) => {
console.log(err);
});
第二个面试题
console.log(1)
function fn(){
new Promise(function(){
console.log(2)
})
}
fn()
console.log(3)
output: 1 2 3
hint: Promise 新建后函数立即执行,直接打印2
异步变同步
const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
output: next now
const f = () => console.log('now');
(async function test() {
f();
})()
console.log('next');
output: now next
async/await
await必须写在async函数里面
// 延时
const promiseFun = function (t) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, t)
})
};
(async function run() {
console.time('tag'); // 记录开始时间
await promiseFun(3000);
console.log('这句话要等到3秒结束后才能打印出来!');
console.timeEnd('tag'); // 记录结束时间
})();
/*
output:
这句话要等到3秒结束后才能打印出来!
tag: 3001.657958984375ms
*/
// return a Promise Object
const fetch = function (t) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, t)
})
};
const get = function () {
return fetch(1000).then(() => {
return 1
})
};
const end = function () {
console.dir(get()); // promise对象
get().then((res) => {
console.log(res); // 1
})
};
end();
// 一些简写形式
const ps = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
name: 'Leon',
age: '18'
}, 1000)
})
})
}
const f = async () => await ps();
!(async function test () {
const res = await f();
console.log(res);
})()
// {name: "Leon", age: "18"}
关于async/await的文章更多的可以看
阮一峰 async 函数的含义和用法
边城 理解 JavaScript 的 async/await
网友评论