1、promise
*1、支持链式调用,可以解决回调地狱问题
* 2、便于异常处理
*
* 中断 promise 链
* 当使用 promise 的 then 链式调用时, 在中间中断, 不再调用后面的回调函数
* 办法: 在回调函数中返回一个 pendding 状态的 promise 对象
function getNumber(){
var p = new Promise(function(resolve, reject){
//做一些异步操作
setTimeout(function(){
var num = Math.ceil(Math.random()*10); //生成1-10的随机数
if(num<=5){
resolve(num);
}
else{
reject('数字太大了');
}
}, 2000);
});
return p;
}
getNumber()
.then(function(data){
console.log('onResolved1',data);
})
.then(data => {
console.log('onResolved2()', data);
return new Promise(() => {}) // 返回一个 pending 的 Promise,中断 promise 链
}
).then( // 这个 then 不会执行力
data => { console.log('onResolved3()', data); }
)
.catch(function(reason){
console.log('rejected');
console.log(reason);
});
2、anync await
* await 必须写在 async 函数中, 但 async 函数中可以没有 await,如果 await 的 Promise 失败了, 就会抛出异常, 需要通过 try...catch 捕获处理
* 正常情况下,await 命令后面是一个 Promise 对象,它也可以跟其他值,如字符串,布尔值,数值以及普通函数。
* await针对所跟不同表达式的处理方式:
Promise 对象:await 会暂停执行,等待 Promise 对象 resolve,然后恢复 async 函数的执行并返回解析值。
非 Promise 对象:直接返回对应的值。
return new Promise((resolve, reject) => {
setTimeout(() => {
// resolve(1000)
reject(1000)
}, 1000);
})
async function fn3() {
try {
const value = await fn2()
} catch (error) {
console.log('得到失败的结果', error)
}
}
fn3() // 得到失败的结果 1000
!!!总结
* Promise.all
* Promise.all([runB(),runA(),runC()]).then((res)=>{console.log(res)})
* promise.all的执行时间取决于 执行时间最长的哪一个函数
* 所以 promise.all 可以用来执行 不关心 执行顺序 只关心 回来结果的 那种需求 优点:执行时间快
*
* async await是语法糖 本质是promise
* 让异步方法 同步执行 执行时间为所有时间总和
* 你关心 函数的执行顺序的话 最好使用 async和await 缺点:执行时间长
Async/await 比 Promise 更优越的表现:
简洁干净,使用 async/await 能省去写多少行代码
错误处理,async/wait 能用相同的结构和好用的经典 try/catch 处理同步和异步错误,错误堆栈能指出包含错误的函数。
调试,async/await 的一个极大优势是它更容易调试,使用 async/await 则无需过多箭头函数,并且能像正常的同步调用一样直接跨过 await 调用。
(async function() {
function buy(event) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(event)
resolve(new Date())
}, 2000)
})
}
function eat(event) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(event)
resolve(new Date())
}, 1000)
})
}
function wash(event) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(event,new Date());
resolve(new Date())
}, 3000)
})
}
/*使用await 之前一定要在它最外层的函数前面写上async
否则会报错
*/
console.log(new Date());
let p1 = await buy('买菜啦')
let p2 = await eat('吃饭啦')
let p3 = await wash('洗碗啦')//执行6秒
// return new Promise((res,rej)=>{
// buy("买菜啦")
// res()
// }).then(()=>{
// eat("吃饭啦")
// }).then((date)=>{
// wash("洗完啦");
// })// 执行时间3秒
// return Promise.all([buy("买菜啦"), eat("吃饭啦"),wash("洗完啦")]) //执行时间3s
})()