前言
在JavaScript中,难免会遇到异步访问的场景,比如打开文件,访问数据库等等。如果不做好异步控制,会导致意外结果,比如:返回值还没返回就想调用,所以就需要用到Promise。
一、Promise是什么?
Promise其实是一个构造函数, 自己身上有all、reject、resolve这些方法,原型上有then、catch这些方法。这么说用Promise new出来的对象肯定就有then、catch方法。
Promise有什么用?
Promise可以让回调变得更简单,更可控。
<script>
getData(a => {
getMoreData(a, b => {
getMoreData(b, c => {
getMoreData(c, d => {
getMoreData(d, e => {
console.log(e);
});
});
});
});
});
</script>
基于当时的困境,然后就有人提出了Promise,从英文看得出,这是一个承诺,承诺我将来会干什么(其实干的事情就是回调)。
如何表征这个回调?在promise后面跟上then表示要回调的函数即可实现
<script>
getData()
.then(a => getMoreData(a))
.then(a => getMoreData(b))
.then(a => getMoreData(c))
.then(a => getMoreData(d))
.then(a => getMoreData(e))
</script>
getData().then(success,fail)表示getData执行后
如果成功(即resolved ,通过return res或者reslove(res)实现),则回调success函数。
如果失败(即rejectd, 通过 throw res或者reject(res)实现),则回调fail函数。
无论任何,res都将传入到相应的回调函数中。而getData().then(success,null).catch(fail)是getData().then(success,fail)的缩略写法。
二、async
async就是异步的意思,也就是说用async修饰的函数是一个异步函数,用法跟别的函数没区别。
<script>
(async function f() {
console.log('111');
console.log('222');
throw '999';
})().then(res => {
console.log(res);
}, res => {
console.log(11);
});
console.log('777');
console.log('1');
console.log('1');
console.log('1');
console.log('1');
</script>
先定义了一个异步函数,然后再执行进入异步函数后,先打印111,然后抛出一个错误。此时,异步函数交出执行权,排在异步函数后面的console.log得以执行,JS是单线程的,直到最后的6打印完毕,才得以处理异步函数抛出的错误,打印11。
异步函数就是用来修饰函数,使该函数异步执行,不阻碍后续函数的执行。
async修饰的函数也带有then catch方法,因此,经async修饰的函数也是一个promise。
三、await
await的意思就是等待,等待await后面的函数执行完毕,异步函数内部再往下执行。await只能放在async中,且只能修饰promise对象。
promise的诞生是为了简化函数嵌套调用流程,也便于后续维护
async/await定义了异步函数,并在其内部可通过await等待promise对象,阻塞后续的执行。
创建promise的方法:
async function f1() {
console.log('777');
return 'haha';
//使用return 'sth'表示执行成功,
//使用throw 'sth'则表示执行失败,'sth'将传递给then
}