一,什么是promise和作用。
特点:
1.三种状态:pending(进行中)、resolved(已完成)、rejected(已失败)。只有异步操作的结果可以决定当前是哪一种状态,任何其他操作都不能改变这个状态。
1.两种状态的转化:其一,从pending(进行中)到resolved(已完成)。其二,从pending(进行中)到rejected(已失败)。只有这两种形式的转变。
1.Promise构造函数的原型对象上,有then()和catch()等方法,then()第一个参数接收resolved()传来的数据,catch()第一个参数接收rejected()传来的数据
作用:
1.通常用来解决异步调用问题
2.解决多层回调嵌套的方案
3.提高代码可读性、更便于维护
二,回调地狱,promise解决回调地狱
1.回调地狱
btn.onclick = function(e) {
p.style.backgroundColor = 'red';
setTimeout(() => {
p.style.backgroundColor = 'yellow';
setTimeout(() => {
p.style.backgroundColor = 'green';
setTimeout(() => {
p.style.backgroundColor = 'blue';
setTimeout(() => {
p.style.backgroundColor = 'black';
setTimeout(() => {
p.style.backgroundColor = 'gray';
setTimeout(() => {
p.style.backgroundColor = 'pink';
}, 1500)
}, 1500)
}, 1500)
}, 1500)
}, 1500)
}, 1000)
}
2.promise解决回调地狱
btn.onclick = function() {
fun1('yellow').then(data => {
p.style.backgroundColor = data;
return fun1('red')
}).then(data => {
p.style.backgroundColor = data;
return fun1('green');
}).then(data => {
p.style.backgroundColor = data;
return fun1('blue');
}).then(data => {
p.style.backgroundColor = data;
return fun1('black', 3000);
}).then(data => {
p.style.backgroundColor = data;
return fun1('gary');
}).then(data => {
p.style.backgroundColor = data;
return fun1('pink');
}).then(data => {
p.style.backgroundColor = data
})
}
function fun1(color, time = 1000) {
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(color);
}, time)
});
return promise;
}
三,async/await
1.
async/await使得异步代码看起来像同步代码。
函数前面多了一个async关键字。await关键字只能用于async定于的函数内。async函数会隐式地返回一个Promise,该promise的resolve值就是return的值。
asyns/await实现
<script>
function fun3() {
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve('定时器3')
}, 3000)
})
}
function fun2() {
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve('定时器2')
}, 2000)
})
}
function fun1() {
return new Promise((resolve, reject) => {
setTimeout(function() {
resolve('定时器1')
}, 1000)
})
}
async function fun() {
// await 关键字仅在 async function 中有效。如果在 async function 函数体外使用 await ,你只会得到一个语法错误。
let rel3 = await fun3()
console.log('rel3', rel3)
let rel2 = await fun2()
console.log('rel2', rel2)
let rel1 = await fun1()
console.log('rel1', rel1)
}
fun()
</script>