Promise、async、await知识点

笔记:掘金

事件循环

开始整个脚本作为一个宏任务
执行过程中同步代码直接执行,宏任务进入宏任务队列,微任务进入微任务队列
当前宏任务执行完出队,检查微任务列表,有则依次执行,直到全部执行完
执行浏览器UI线程的渲染工作
检查是否有Web Worker任务,有则执行
执行完本轮的宏任务,回到2,依次循环,直到宏任务和微任务队列都为空

微任务包括:MutationObserver、Promise.then()或catch()、Promise为基础开发的其它技术,比如fetch API、V8的垃圾回收过程、Node独有的process.nextTick。
宏任务包括:script 、setTimeout、setInterval 、setImmediate 、I/O 、UI rendering。
注意⚠️:在所有任务开始的时候,由于宏任务中包括了script,所以浏览器会先执行一个宏任务,在这个过程中你看到的延迟任务(例如setTimeout)将被放到下一轮宏任务中来执行。

相关习题

Promise

题目1

const promise1 = new Promise((resolve, reject) => {
  console.log('promise1')
})
console.log('1', promise1);

在这里插入图片描述

题目2

const promise = new Promise((resolve, reject) => {
  console.log(1);
  resolve('success')
  console.log(2);
});
promise.then(() => {
  console.log(3);
});
console.log(4);

在这里插入图片描述

题目3

const promise = new Promise((resolve, reject) => {
  console.log(1);
  console.log(2);
});
promise.then(() => {
  console.log(3);
});
console.log(4);
  • 此时promise中并没有resolve或者reject,因此promise.then并不会执行,它只有被改变了状态之后才会执行

1 2 4

题目4

const promise1 = new Promise((resolve, reject) => {
  console.log('promise1')
  resolve('resolve1')
})
const promise2 = promise1.then(res => {
  console.log(res)
})
console.log('1', promise1);
console.log('2', promise2);

在这里插入图片描述

  • 从上到下,先遇到new Promise ,执行该构造函数中的代码promise1
  • 碰到resolve函数,将promise1的状态改变为resolved,并将结果保存下来
  • 碰到promise1.then这个微任务,将他放在微任务队列中
  • promise2是一个新的状态为pending的promise
  • 执行同步代码1,同时带引promise1的状态
  • 自行同步代码2,同时打印promise2的状态
  • 宏任务执行完毕,查找微任务队列,发现promise1.then这个微任务状态为resolved,执行

题目5

const fn = () => (new Promise((resolve, reject) => {
  console.log(1);
  resolve('success')
}))
fn().then(res => {
  console.log(res)
})
console.log('start')

1 start success

  • 此时fn是一个函数,它是直接返回了一个new Promise,而且fn函数的调用是在start之前,所以里面的内容会先执行

题目6

const fn = () =>
  new Promise((resolve, reject) => {
    console.log(1);
    resolve("success");
  });
console.log("start");
fn().then(res => {
  console.log(res);
});

start 1 success

  • 现在start在1之前打印,因为fn函数是之后执行的

注意: 之前我们很容易就以为看到new Promise()就执行它的第一个参数函数了,其实这是不对的,就像这两道题中,我们得注意它是不是被包裹在函数当中,如果是的话,只有在函数调用的时候才会执行。

Promise+setTimeout

题目1

console.log('start')
setTimeout(() => {
  console.log('time')
})
Promise.resolve().then(() => {
  console.log('resolve')
})
console.log('end')

start end resolve time

  • 刚开始整个脚本作为一个宏任务来执行,对于同步代码直接压入执行栈进行执行,因此先打印start和end
  • setTimeout作为一个宏任务,进入下一个宏任务队列
  • Promise.then作为一个微任务被放入微任务队列
  • 本次宏任务执行完毕,检查微任务执行
    -进入下一个宏任务执行

题目2

const promise = new Promise((resolve, reject) => {
  console.log(1);
  setTimeout(() => {
    console.log("timerStart");
    resolve("success");
    console.log("timerEnd");
  }, 0);
  console.log(2);
});
promise.then((res) => {
  console.log(res);
});
console.log(4);

1 2 4 timerstart timerend success

  • 从上到下,先遇到new Promise,执行该函数中的代码1
  • 然后遇到定时器,将定时器中的函数放到下一个宏任务的延迟队列中等待执行
  • 执行同步代码4
  • 跳出promise函数,遇到promise.then,但是其状态还是pending,先不执行
  • 执行同步代码4
  • 一轮循环过后,进入第二次宏任务,发现延迟队列中还有setTimout定时器,执行
  • 首先执行timerstart,然后遇到resolve,将promise的状态改为resolved。且保存结果并将之前的promise.then推入微任务队列
  • 继续执行同步代码timerend
  • 宏任务全部执行完毕,查找微任务,发现promise.then这个微任务并执行

题目3

setTimeout(() => {
  console.log('timer1');
  setTimeout(() => {
    console.log('timer3')
  }, 0)
}, 0)
setTimeout(() => {
  console.log('timer2')
}, 0)
console.log('start')

start timer1 timer2 timer3

setTimeout(() => {
  console.log('timer1');
  Promise.resolve().then(() => {
    console.log('promise')
  })
}, 0)
setTimeout(() => {
  console.log('timer2')
}, 0)
console.log('start')

start timer1 promise timer2

  • 如果是定时器timer3的话,它会在timer2后执行,而Promise.then却是在timer2之前执行。
  • Promise.then是微任务,它会被加入到本轮中的微任务列表,而定时器timer3是宏任务,它会被加入到下一轮的宏任务中。
Promise.resolve().then(() => {
  console.log('promise1');
  const timer2 = setTimeout(() => {
    console.log('timer2')
  }, 0)
});
const timer1 = setTimeout(() => {
  console.log('timer1')
  Promise.resolve().then(() => {
    console.log('promise2')
  })
}, 0)
console.log('start');

start promise1 timer1 promise2 timer2

在这里插入图片描述

题目4

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  }, 1000)
})
const promise2 = promise1.then(() => {
  throw new Error('error!!!')
})
console.log('promise1', promise1)
console.log('promise2', promise2)
setTimeout(() => {
  console.log('promise1', promise1)
  console.log('promise2', promise2)
}, 2000)
  • 从上到下,先执行第一个new Promise中的函数,碰到setTimeout将他加入到下一个宏任务列表中
  • 跳出new Promise,碰到promise.then这个微任务,他的状态还是pending,状态,因此先不执行
  • 执行同步代码,console.log(‘promise1’),且打印出的promise1的状态为pending
  • 执行同步代码console.log(‘promise2’),且打印出的promise2的状态为pending
  • 碰到第二个定时器,将其放入到下一个宏任务列表中
  • 第一轮宏任务执行结束,并且没有微任务需要执行,因此执行第二轮宏任务
  • 先执行第一个定时器里的内容,将promise1的状态改为resolved且保存结果并将之前的promise1.then推入微任务队列
  • 该定时器中没有其它的同步代码可执行,因此执行本轮的微任务队列,也就是promise1.then,它抛出了一个错误,且将promise2的状态设置为了rejected
  • 第一个定时器执行完毕,开始执行第二个定时器中的内容
  • 打印出’promise1’,且此时promise1的状态为resolved
  • 打印出’promise2’,且此时promise2的状态为rejected

在这里插入图片描述

题目5

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("success");
    console.log("timer1");
  }, 1000);
  console.log("promise1里的内容");
});
const promise2 = promise1.then(() => {
  throw new Error("error!!!");
});
console.log("promise1", promise1);
console.log("promise2", promise2);
setTimeout(() => {
  console.log("timer2");
  console.log("promise1", promise1);
  console.log("promise2", promise2);
}, 2000);

在这里插入图片描述

Promise中的then、catch、finally

  1. Promise的状态一经过改变就不会再改变了
  2. .then 和.catch都会返回一个新的Promise
  3. catch不管被连接到哪里,都能捕获上层未捕获到的错误
  4. 在Promise中,返回任意一个非 promise 的值都会被包裹成 promise 对象,例如return 2会被包装为return Promise.resolve(2)。
  5. Promise 的 .then 或者 .catch 可以被调用多次, 但如果Promise内部的状态一经改变,并且有了一个值,那么后续每次调用.then或者.catch的时候都会直接拿到该值。
  6. .then 或者 .catch 中 return 一个 error 对象并不会抛出错误,所以不会被后续的 .catch 捕获。
  7. .then 或 .catch 返回的值不能是 promise 本身,否则会造成死循环
  8. .then 或者 .catch 的参数期望是函数,传入非函数则会发生值透传
  9. .then方法是能接收两个参数的,第一个是处理成功的函数,第二个是处理失败的函数,再某些时候你可以认为catch是.then第二个参数的简便写法。
  10. .finally方法也是返回一个Promise,他在Promise结束的时候,无论结果为resolved还是rejected,都会执行里面的回调函数。

题目1

const promise = new Promise((resolve, reject) => {
  resolve("success1");
  reject("error");
  resolve("success2");
});
promise
.then(res => {
    console.log("then: ", res);
  }).catch(err => {
    console.log("catch: ", err);
  })

Promise的状态一经过改变就不会再改变了

then: success1

题目2

const promise = new Promise((resolve, reject) => {
  reject("error");
  resolve("success2");
});
promise
.then(res => {
    console.log("then1: ", res);
  }).then(res => {
    console.log("then2: ", res);
  }).catch(err => {
    console.log("catch: ", err);
  }).then(res => {
    console.log("then3: ", res);
  })
  • catch不管被连接到哪里,都能捕获上层未捕获到的错误
  • .then 和.catch都会返回一个新的Promise
  • then3也会被执行,那是因为catch()也会返回一个Promise,且由于这个Promise没有返回值,所以打印出来的是undefined

catch: error then3: undefined

题目3

Promise.resolve(1)
  .then(res => {
    console.log(res);
    return 2;
  })
  .catch(err => {
    return 3;
  })
  .then(res => {
    console.log(res);
  });
  • Promise可以链式调用,不过promise 每次调用 .then 或者 .catch 都会返回一个新的 promise,从而实现了链式调用, 它并不像一般我们任务的链式调用一样return this。
  • 因为resolve(1)之后走的是第一个then方法,并没有走catch里,所以第二个then中的res得到的实际上是第一个then的返回值。
  • catch用来捕获错误,其中并没有被执行

1 2

题目4

Promise.reject(1)
  .then(res => {
    console.log(res);
    return 2;
  })
  .catch(err => {
    console.log(err);
    return 3
  })
  .then(res => {
    console.log(res);
  });

1 3

题目5

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('timer')
    resolve('success')
  }, 1000)
})
const start = Date.now();
promise.then(res => {
  console.log(res, Date.now() - start)
})
promise.then(res => {
  console.log(res, Date.now() - start)
})

‘timer’ ‘success’ 1001 ‘success’ 1002

  • 可能两个都是1001。
  • promise的.then或者.catch可以被调用多次,但是这里的promise构造函数只执行一次。或者说 promise 内部状态一经改变,并且有了一个值,那么后续每次调用 .then 或者 .catch 都会直接拿到该值。

题目6

Promise.resolve().then(() => {
  return new Error('error!!!')
}).then(res => {
  console.log("then: ", res)
}).catch(err => {
  console.log("catch: ", err)
})
  • .then 或者 .catch 中 return 一个 error 对象并不会抛出错误,所以不会被后续的 .catch 捕获。

"then: " “Error: error!!!”

如果想抛出一个错误的话,应该用

return Promise.reject(new Error('error!!!'));
// or
throw new Error('error!!!')

题目7

const promise = Promise.resolve().then(() => {
  return promise;
})
promise.catch(console.err)

.then 或 .catch 返回的值不能是 promise 本身,否则会造成死循环

Uncaught (in promise) TypeError: Chaining cycle detected for promise #

题目8

Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .then(console.log)

.then 或者 .catch 的参数期望是函数,传入非函数则会发生值透传。
第一个then和第二个then中传入的都不是函数,一个是数字类型,一个是对象类型,因此发生了透传

1

题目9

Promise.reject('err!!!')
  .then((res) => {
    console.log('success', res)
  }, (err) => {
    console.log('error', err)
  }).catch(err => {
    console.log('catch', err)
  })

进入到err这个函数中,就不会再被catch捕获了。如果删掉err这个函数,那么这个错误就会被catch捕获

error err!!!

Promise.resolve()
  .then(function success (res) {
    throw new Error('error!!!')
  }, function fail1 (err) {
    console.log('fail1', err)
  }).catch(function fail2 (err) {
    console.log('fail2', err)
  })
  • 由于promise调用的是resolve(),因此.then执行的是success()函数,可以success函数抛出的是一个错误,他会被后面的catch()捕获到,而不是被fail函数捕获

fail2 Error: error!!!
at success (demo.html:11:11)

题目10 .finally

  • .finally方法也是返回一个Promise,他在Promise结束的时候,无论结果为resolved还是rejected,都会执行里面的回调函数。
  • 最终返回的默认会是上一次的Promise对象值,不过如果抛出的是一个异常则会返回异常的promise对象
Promise.resolve('1')
  .then(res => {
    console.log(res)
  })
  .finally(() => {
    console.log('finally')
  })
Promise.resolve('2')
  .finally(() => {
    console.log('finally2')
  	return '我是finally2返回的值'
  })
  .then(res => {
    console.log('finally2后面的then函数', res)
  })
  • 微任务排队
  • 这两个promise的.finally都会执行,并且就算finally2返回了新值,后面的them()函数接受的结果还是2

‘1’ ‘finally2’ ‘finally’ ‘finally2后面的then函数’ ‘2’

Promise.resolve('1')
  .finally(() => {
    console.log('finally1')
    throw new Error('我是finally中抛出的异常')
  })
  .then(res => {
    console.log('finally后面的then函数', res)
  })
  .catch(err => {
    console.log('捕获错误', err)
  })

‘finally1’ ‘捕获错误’ Error: 我是finally中抛出的异常

function promise1 () {
  let p = new Promise((resolve) => {
    console.log('promise1');
    resolve('1')
  })
  return p;
}
function promise2 () {
  return new Promise((resolve, reject) => {
    reject('error')
  })
}
promise1()
  .then(res => console.log(res))
  .catch(err => console.log(err))
  .finally(() => console.log('finally1'))

promise2()
  .then(res => console.log(res))
  .catch(err => console.log(err))
  .finally(() => console.log('finally2'))
  • 首先定义了两个而寒暑promise1,和promise2
  • promise1先被调用,然后执行里面的new promise的同步代码,先打印promise1
  • 之后遇到resolve(1),将p的状态改变为resolved并保存
  • 此时promise1函数内容执行完毕,跳出函数
  • 遇到promise1().then()由于promise1的状态已经发送了改变,因此将其加入本轮的微任务(1)
  • 这时候要注意了,代码并不会接着往链式调用的下面走,也就是不会先将.finally加入微任务列表, 那是因为.then本身就是一个微任务,它链式后面的内容必须得等当前这个微任务执行完才会执行, 因此这里我们先不管.finally()
  • 再往下走碰到了promise2()函数,其中返回的new Promise中并没有同步代码需要执行,所以执行reject(‘error’)的时候将promise2函数中的Promise的状态变为了rejected
  • 跳出promise2函数,遇到了promise2().catch(),将其加入当前的微任务队列(这是第二个微任务),且链式调用后面的内容得等该任务执行完后才执行,和.then()一样。
  • OK, 本轮的宏任务全部执行完了,来看看微任务列表,存在promise1().then(),执行它,打印出1,然后遇到了.finally()这个微任务将它加入微任务列表(这是第三个微任务)等待执行
  • 再执行promise2().catch()打印出error,执行完后将finally2加入微任务加入微任务列表(这是第四个微任务)
  • OK, 本轮又全部执行完了,但是微任务列表还有两个新的微任务没有执行完,因此依次执行finally1和finally2。

‘promise1’ ‘1’ ‘error’ ‘finally1’ ‘finally2’

Promise中的all和race

.all() 的作用是接收一组异步任务,然后 并行执行异步任务, 并且在所有异步操作执行完后才执行回调
.race() 的作用也是接收一组异步任务,然后并行执行异步任务,只保留取第一个执行完成的异步操作的结果,其他的方法仍在执行,不过执行结果会被抛弃。

题目1

function runAsync (x) {
    const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
    return p
}
Promise.all([runAsync(1), runAsync(2), runAsync(3)])
  .then(res => console.log(res))
  • 在间隔一秒后,控制台会同时打印出1, 2, 3,还有一个数组[1, 2, 3]。
  • 有了all,可以并行执行多个异步操作,并且在一个回调中处理所有返回数据
  • .all()后面的.then()里的回调函数接受的就是所有异步操作的结果

1 2 3 [1, 2, 3]
适用场景:一些游戏类的素材比较多的应用,打开网页时,预先加载需要用到的各种资源如图片、flash以及各种静态文件。所有的都加载完后,我们再进行页面的初始化。

题目2

function runAsync (x) {
  const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
  return p
}
function runReject (x) {
  const p = new Promise((res, rej) => setTimeout(() => rej(`Error: ${x}`, console.log(x)), 1000 * x))
  return p
}
Promise.all([runAsync(1), runReject(4), runAsync(3), runReject(2)])
  .then(res => console.log(res))
  .catch(err => console.log(err))

// 1s后输出
1
3
// 2s后输出
2
Error: 2
// 4s后输出
4

  • .catch会捕获最先的那个异常
  • 如果一组异步操作中有一个异常,就都不会进入.then()的第一个回调函数中

题目3

function runAsync (x) {
  const p = new Promise(r => setTimeout(() => r(x, console.log(x)), 1000))
  return p
}
Promise.race([runAsync(1), runAsync(2), runAsync(3)])
  .then(res => console.log('result: ', res))
  .catch(err => console.log(err))

.race()方法,它只会获取最先执行完成的那个结果,其它的异步任务虽然也会继续进行下去,不过race已经不管那些任务的结果了。

1
'result: ’ 1
2
3

  • 使用场景:可以用race给某个异步请求设置超时事件,且在超时后执行相应的操作

题目4

function runAsync(x) {
  const p = new Promise(r =>
    setTimeout(() => r(x, console.log(x)), 1000)
  );
  return p;
}
function runReject(x) {
  const p = new Promise((res, rej) =>
    setTimeout(() => rej(`Error: ${x}`, console.log(x)), 1000 * x)
  );
  return p;
}
Promise.race([runReject(0), runAsync(1), runAsync(2), runAsync(3)])
  .then(res => console.log("result: ", res))
  .catch(err => console.log(err));

runReject(0)最先执行完,所以进入了catch()中

0
‘Error: 0’
1
2
3

总结

  1. Promise.all()的作用是接收一组异步任务,然后并行执行异步任务,并且在所有异步操作执行完后才执行回调
  2. .race()的作用也是接收一组异步任务,然后并行执行异步任务,只保留取第一个执行完成的异步操作的结果,其他的方法仍在执行,不过执行结果会被抛弃。
  3. Promise.all().then()结果中数组的顺序和Promise.all()接收到的数组顺序一致。
  4. all和race传入的数组中如果有会抛出异常的异步任务,那么只有最先抛出的错误会被捕获,并且是被then的第二个参数或者后面的catch捕获;但并不会影响数组中其它的异步任务的执行。

async/await

宏任务主要包括:
1、script(整体代码) 2、setTimeout 3、setInterval 4、I/O 5、UI交互事件 6、postMessage 7、MessageChannel 8、setImmediate
微任务主要包括:
1、Promise.then 2、MutationObserver 3、process.nextTick

Promise中的异步任务体现在then和catch中,所以写在Promise中的代码是被当做同步任务立即执行的,而在async/await中,出现在await之前。其中的代码也是立即执行

实际上await是一个让出线程的标志,await后面的表达式会先执行一遍,将await后面的代码加入到microtask中。然后就会跳出整个async函数来执行后面的代码

题目1

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
  console.log("async2");
}
async1();
console.log('start')

‘async1 start’ ‘async2’ ‘start’ ‘async1 end’

  • 首先创建两个函数,先不看函数的创建位置,而是看他的调用位置
  • async1先调用
  • 执行函数中的同步代码async1 start,之后碰到await,会阻塞async1后面的代码的执行,因此会先执行async2中的同步代码,之后跳出async1
  • 跳出async1后,执行同步代码start
  • 在一轮宏任务全部执行完之后,再执行await后面的内容aync1 end

紧跟着await后面的语句相当于放到了new Promise中,下一行及之后的语句相当于放在Promise.then中

等价于

async function async1() {
  console.log("async1 start");
  // 原来代码
  // await async2();
  // console.log("async1 end");
  
  // 转换后代码
  new Promise(resolve => {
    console.log("async2")
    resolve()
  }).then(res => console.log("async1 end"))
}
async function async2() {
  console.log("async2");
}
async1();
console.log("start")
async function async1() {
  console.log("async1 start");
  new Promise(resolve => {
    console.log('promise')
  })
  console.log("async1 end");
}
async1();
console.log("start")

‘async start’ ‘promise’ ‘async1 end’ ‘start’

new Promise()并不会阻塞后面的同步代码async1 end的执行

题目2

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
  setTimeout(() => {
    console.log('timer')
  }, 0)
  console.log("async2");
}
async1();
console.log("start")

在这里插入图片描述
为什么start会在前面呢
一整个代码都是一个宏任务

题目3

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
  setTimeout(() => {
    console.log('timer1')
  }, 0)
}
async function async2() {
  setTimeout(() => {
    console.log('timer2')
  }, 0)
  console.log("async2");
}
async1();
setTimeout(() => {
  console.log('timer3')
}, 0)
console.log("start")`在这里插入代码片`

在这里插入图片描述
定时器谁先执行,你只需要关注谁先被调用的以及延迟时间是多少,这道题中延迟时间都是0,所以只要关注谁先被调用的。

题目4

正常情况下,async中的await命令是一个Promise对象,返回该对象的结果。

但如果不是Promise对象的话,就会直接返回对应的值,相当于Promise.resolve()

async function fn () {
  // return await 1234
  // 等同于
  return 123
}
fn().then(res => console.log(res))

123

题目5

async function async1 () {
  console.log('async1 start');
  await new Promise(resolve => {
    console.log('promise1')
  })
  console.log('async1 success');
  return 'async1 end'
}
console.log('srcipt start')
async1().then(res => console.log(res))
console.log('srcipt end')

在这里插入图片描述

  • 在async1中await后面的promise是没有返回值的。它的状态一致是pending状态
  • 相当于一直在await,await,await却始终没有响应…
  • 所以在await之后的内容是不会执行的,也包括async1后面的 .then

题目6

async function async1 () {
  console.log('async1 start');
  await new Promise(resolve => {
    console.log('promise1')
    resolve('promise1 resolve')
  }).then(res => console.log(res))
  console.log('async1 success');
  return 'async1 end'
}
console.log('srcipt start')
async1().then(res => console.log(res))
console.log('srcipt end')
  • 现在Promise有了返回值了,因此await后面的内容将会被执行:

在这里插入图片描述

题目7

async function async1 () {
  console.log('async1 start');
  await new Promise(resolve => {
    console.log('promise1')
    resolve('promise resolve')
  })
  console.log('async1 success');
  return 'async1 end'
}
console.log('srcipt start')
async1().then(res => {
  console.log(res)
})
new Promise(resolve => {
  console.log('promise2')
  setTimeout(() => {
    console.log('timer')
  })
})

在这里插入图片描述

  • 注意,在async1中的new Promise它的resovle的值和async1().then()里的值是没有关系的

题目8

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}

async function async2() {
  console.log("async2");
}

console.log("script start");

setTimeout(function() {
  console.log("setTimeout");
}, 0);

async1();

new Promise(function(resolve) {
  console.log("promise1");
  resolve();
}).then(function() {
  console.log("promise2");
});
console.log('script end')

在这里插入图片描述

题目9

async function testSometing() {
  console.log("执行testSometing");
  return "testSometing";
}

async function testAsync() {
  console.log("执行testAsync");
  return Promise.resolve("hello async");
}

async function test() {
  console.log("test start...");
  const v1 = await testSometing();
  console.log(v1);
  const v2 = await testAsync();
  console.log(v2);
  console.log(v1, v2);
}

test();

var promise = new Promise(resolve => {
  console.log("promise start...");
  resolve("promise");
});
promise.then(val => console.log(val));

console.log("test end...");

在这里插入图片描述

[返回值] = await 表达式;
返回值:返回 Promise 对象的处理结果。如果等待的不是 Promise 对象,则返回该值本身。
如果一个promise被传递给一个await操作符,await将等待promise正常处理完成并返回其处理结果
在这里插入图片描述
如果这个值不是一个promise,await会把这个值转换为已经正常处理的promise,然后等待其返回处理结果
在这里插入图片描述
如果promise处理异常,则异常会被抛出
在这里插入图片描述

题目10

链接:https://www.nowcoder.com/questionTerminal/4f3e5781b29646a68965e1e9870400cb
来源:牛客网

async function foo() {
  console.log(2);
  console.log(await Promise.resolve(8));
  console.log(9); 
  console.log(await Promise.resolve(18));
  console.log(19);
}
async function bar() {
  console.log(4);
  console.log(await 6);
  console.log(7);
}
console.log(1);
foo();
console.log(3);
bar();
console.log(5);

1234589671819

async处理错误

题目1

async function async1 () {
  await async2();
  console.log('async1');
  return 'async1 success'
}
async function async2 () {
  return new Promise((resolve, reject) => {
    console.log('async2')
    reject('error')
  })
}
async1().then(res => console.log(res))
  • await后面跟着一个状态为rejected的promise
    ** 如果在async函数中抛出了错误,则终止错误结果,不会继续向下执行**

‘async2’ Uncaught (in promise) error

题目2

try-catch用法

异常处理的目的是捕捉产生异常的代码,使整个程序不会因为异常而终止运行,可以使用try…catch语句来捕获异常,并做相应的处理:

try {
    // 可能会发生异常的代码
} catch(error) {
    // 发生异常时要执行的操作
}

可以将任何可能发生异常的代码放到try语句中,并在catch中定义处理异常的方法,如果try语句块中的代码发生错误,代码会立即从try语句块跳转到catch语句块中,如果没有发生错误,就会忽略catch语句块中的代码。

async function async1 () {
  try {
    await Promise.reject('error!!!')
  } catch(e) {
    console.log(e)
  }
  console.log('async1');
  return Promise.resolve('async1 success')
}
async1().then(res => console.log(res))
console.log('script start')

‘script start’ ‘error!!!’ ‘async1’

async function async1 () {
  // try {
  //   await Promise.reject('error!!!')
  // } catch(e) {
  //   console.log(e)
  // }
  await Promise.reject('error!!!')
    .catch(e => console.log(e))
  console.log('async1');
  return Promise.resolve('async1 success')
}
async1().then(res => console.log(res))
console.log('script start')
try-catch-finally

无论try语句块中的代码是否发生错误,finally语句中的代码都会执行

综合题

题目 1

const first = () => (new Promise((resolve, reject) => {
    console.log(3);
    let p = new Promise((resolve, reject) => {
        console.log(7);
        setTimeout(() => {
            console.log(5);
            resolve(6);
            console.log(p)
        }, 0)
        resolve(1);
    });
    resolve(2);
    p.then((arg) => {
        console.log(arg);
    });
}));
first().then((arg) => {
    console.log(arg);
});
console.log(4);

在这里插入图片描述

  • 第一段代码定义的是一个函数,所以我们得看看它是在哪执行的,发现它在4之前,所以可以来看看first函数里面的内容了
  • 函数first返回的是一个new Promise(),因此先执行里面的同步代码3
  • 接着又遇到了一个new Promise(),直接执行里面的同步代码7
  • 执行完7之后,在p中,遇到了一个定时器,先将它放到下一个宏任务队列里不管它,接着向下走
  • 碰到了resolve(1),这里就把p的状态改为了resolved,且返回值为1,不过这里也先不执行
  • 出p,碰到了resolve(2),这里的resolve(2),表示的是把first函数返回的那个Promise的状态改了,也先不管它。
  • 然后碰到了p.then,将它加入本次循环的微任务列表,等待执行
  • 跳出first函数,遇到了first().then(),将它加入本次循环的微任务列表(p.then的后面执行)
  • 然后执行同步代码4
  • 本轮的同步代码全部执行完毕,查找微任务列表,发现p.then和first().then(),依次执行,打印出1和2
  • 本轮任务执行完毕了,发现还有一个定时器没有跑完,接着执行这个定时器里的内容,执行同步代码5
  • 然后又遇到了一个resolve(6),它是放在p里的,但是p的状态在之前已经发生过改变了,因此这里就不会再改变,也就是说resolve(6)相当于没任何用处,因此打印出来的p为Promise{: 1}。

题目2

const async1 = async () => {
  console.log('async1');
  setTimeout(() => {
    console.log('timer1')
  }, 2000)
  await new Promise(resolve => {
    console.log('promise1')
  })
  console.log('async1 end')
  return 'async1 success'
} 
console.log('script start');
async1().then(res => console.log(res));
console.log('script end');
Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .catch(4)
  .then(res => console.log(res))
setTimeout(() => {
  console.log('timer2')
}, 1000)

在这里插入图片描述

  • async函数中await的new promise要是没有返回值的话就不会执行后面的内容
  • .then函数中的参数期待的是函数,如果不是函数的话救护发送透传
  • 注意定时器的延时时间
const async1 = async () => {
  console.log('async1');
  setTimeout(() => {
    console.log('timer1')
  }, 2000)
  await new Promise(resolve => {
    console.log('promise1')
    resolve()
  })
  console.log('async1 end')
  return 'async1 success'
} 
console.log('script start');
async1().then(res => console.log(res));
console.log('script end');
Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .catch(4)
  .then(res => console.log(res))
setTimeout(() => {
  console.log('timer2')
}, 1000)

在这里插入图片描述

题目3

const p1 = new Promise((resolve) => {
  setTimeout(() => {
    resolve('resolve3');
    console.log('timer1')
  }, 0)
  resolve('resovle1');
  resolve('resolve2');
}).then(res => {
  console.log(res)
  setTimeout(() => {
    console.log(p1)
  }, 1000)
}).finally(res => {
  console.log('finally', res)
})
  • promise的状态一旦改变就无法改变
  • finally不管promise的状态时resolved还是rejected都会执行,且他的回调函数是接受不到promise的结果的,所以finally中的res是undefined
  • 最后一个定时器打印出的p1其实是finally的返回值,因为finally的返回值如果在没有抛出错误的情况下默认会是上一个promise的返回值 ,在这里,finally上一个promise是.then(),但是这个.then并没有返回值,所以p1打出的promise会是一个undefined。如果在定时器下面加上一个return1 值就会变为1

‘resolve1’
‘finally’ undefined
‘timer1’
Promise{: undefined}

实现题

使用promise实现每个1秒输出1,2,3

let p1=new Promise(resolve=>{
setTimeout(()=>{
console.log(1)
resolve()
},1000)
})
p1.then(resolve=>{
  setTimeout(()=>{
    console.log(2)
new Promise(resolve=>{//应该在这里再返回一个新的promise
  setTimeout(()=>{
    console.log(3)
  },1000)
})
  },1000)
}) 

Promise的优势在于,可以在then中继续写Promise对象并返回,然后继续调用then来进行回调操作
Promise().then()既然返回的是一个Promise对象, 那么then()中应该有类似于Promise((resolve, reject)=>{})中的resolve和reject的参数,以便向后传递继续(when resolved)或者中断(when rejected)的信息. 但是, then()中只接受两个函数:handleFulfilled,handleRejected, 并且这两个函数中的参数只有一个, 就是上一个Promise中resolve出来的或reject出来的.
因此在.then()中使用return和throw

async function p1(){
 await new Promise(resolve=>{
  setTimeout(()=>{
    console.log(1)
    resolve()
  },1000)
 })
 await new Promise(resolve=>{
  setTimeout(()=>{
    console.log(2)
    resolve()
  },1000)
 })
 await new Promise(resolve=>{
  setTimeout(()=>{
    console.log(3)
  },1000)
 })
}
p1()

结合reduce

一定要记得 new Promise(executor) 的 executor 是马上执行的。
所以要么递增 timeout 的时间,要么在一个 Promise resolved 之后再创建新的 Promise。

const arr=[1,2,3,4]
arr.reduce((p,x)=>{
  return p.then(()=>{
    return new Promise(r=>{
      setTimeout(()=>{
        r(console.log(x))
      },1000)
    })
  })
},Promise.resolve())

改造

const arr = [1, 2, 3];
const result = arr.reduce((p, x) => p.then(new Promise(r => setTimeout(() => r(console.log(x)), 1000))), Promise.resolve());

此时为什么会同时打印1,2,3
类似于一直.then .then

使用Promise实现红绿灯交替重复亮

红灯3秒亮一次,黄灯2秒亮一次,绿灯1秒亮一次;如何让三个灯不断交替重复亮灯?(用Promise实现)三个亮灯函数已经存在:

function red() {
    console.log('red');
}
function green() {
    console.log('green');
}
function yellow() {
    console.log('yellow');
}

解决:

function red1(){
  return new Promise(resovle=>{
    setTimeout(()=>{
      red()
      resovle()
    },3000)
  }).then(()=>{
    yellow1()
  })
}
function green1(){
  return new Promise(resovle=>{
    setTimeout(()=>{
      green()
      resovle()
    },1000)
  }).then(()=>{red1()})
}
function yellow1(){
  return new Promise(resovle=>{
    setTimeout(()=>{
      yellow()
      resovle()
    },2000)
  }).then(()=>{green1()})
}
red1()

或者

const light=function(timer,cb){
  return new Promise(resolve=>{
    setTimeout(()=>{
      cb()
      resolve()
    },timer)
  })
}
const step=function(){
  Promise.resolve().then(()=>{
    return light(3000,red)
  }).then(()=>{
    return light(2000,green)
  }).then(()=>{
    return light(1000,yellow)
  }).then(()=>{
    return step()
  })
}
step()

实现mergePromise函数

实现mergePromise函数,把传进去的数组按顺序先后执行,并且把返回的数据先后放到数组data中。

const time = (timer) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, timer)
  })
}
const ajax1 = () => time(2000).then(() => {
  console.log(1);
  return 1
})
const ajax2 = () => time(1000).then(() => {
  console.log(2);
  return 2
})
const ajax3 = () => time(1000).then(() => {
  console.log(3);
  return 3
})

function mergePromise () {
  // 在这里写代码
}

mergePromise([ajax1, ajax2, ajax3]).then(data => {
  console.log("done");
  console.log(data); // data 为 [1, 2, 3]
});

解决

function mergePromise () {
  // 在这里写代码
  let result=[]
  let b=[...arguments][0]
async function print(){
let re1=await b[0]()
result.push(re1)
let re2=await b[1]()
result.push(re2)
let re3=await b[2]()
result.push(re3)
return new Promise(resolve=>{
  resolve(result)
})
}
return print()
}

要拿到上一次promise的执行结果,那就只能用await?
结果:

类似Promise.all(),但是.all()不需要管执行顺序,只需要并发执行,但是这里需要等到上一个执行完毕才能执行下一个

思路:
首先定义一个数组data用于保存所有异步操作的结果
初始化一个const promise=Promise.resolve(),然后遍历循环数组,在promise后面添加执行ajax任务,同时将添加的结果重新赋值到.promise上面

function mergePromise (ajaxArry) {
  // 在这里写代码
  let data=[]
  let promise=Promise.resolve();//不是new Promise.resolve()
  ajaxArry.forEach(ajax=>{
    //第一次的then是为了调用ajax
    //第二次的then是为了获取ajax的结果
    promise=promise.then(ajax).then(res=>{
      data.push(res)
    return data//把每次的结果返回
    })
  })
  //最后得到的promise他的值就是data
  return promise
}

封装一个异步加载图片的方法

只需要在图片的onload函数中,使用resolve返回一下就可以了。

function loadImg(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = function() {
      console.log("一张图片加载完成");
      resolve(img);
    };
    img.onerror = function() {
    	reject(new Error('Could not load image at' + url));
    };
    img.src = url;
  });
<div></div>
let div=document.querySelector('div')
var urls = [
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting1.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting2.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting3.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting4.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting5.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn6.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn7.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn8.png",
];
function loadImg(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = function() {
      console.log("一张图片加载完成");
      resolve(img);
    };
    img.onerror = function() {
    	reject(new Error('Could not load image at' + url));
    };
    img.src = url;
  });
}
loadImg(urls[0]).then((res)=>{
  console.log(res);
 div.appendChild(res)
})

限制异步操作的并发个数并尽可能快的完成全部

有8个图片资源的url,已经存储在数组urls中。
urls类似于[‘https://image1.png’, ‘https://image2.png’, …]
而且已经有一个函数function loadImg,输入一个url链接,返回一个Promise,该Promise在图片下载完成的时候resolve,下载失败则reject。
但有一个要求,任何时刻同时下载的链接数量不可以超过3个。
请写一段代码实现这个需求,要求尽可能快速地将所有图片下载完成。

题目的要求是保证每次并发请求的数量为3,那么我们可以先请求urls中的前面三个(下标为0,1,2),并且请求的时候使用Promise.race()来同时请求,三个中有一个先完成了(例如下标为1的图片),我们就把这个当前数组中已经完成的那一项(第1项)换成还没有请求的那一项(urls中下标为3)。
直到urls已经遍历完了,然后将最后三个没有完成的请求(也就是状态没有改变的Promise)用Promise.all()来加载它们。请添加图片描述

        <div></div>

        <script>
let div=document.querySelector('div')
var urls = [
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting1.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting2.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting3.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting4.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting5.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn6.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn7.png",
  "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn8.png",
];
function loadImg(url) {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = function() {
      console.log("一张图片加载完成");
      resolve(img);
    };
    img.onerror = function() {
    	reject(new Error('Could not load image at' + url));
    };
    img.src = url;
  });
}

function limitLoad(urls, handler, limit) {
  let sequence = [].concat(urls); // 复制urls
  // 这一步是为了初始化 promises 这个"容器"
  let promises = sequence.splice(0, limit).map((url, index) => {
    return handler(url).then(() => {
      // 返回下标是为了知道数组中是哪一项最先完成
      return index;
    });
  });
  // 注意这里要将整个变量过程返回,这样得到的就是一个Promise,可以在外面链式调用
  return sequence
    .reduce((pCollect, url) => {
      return pCollect
        .then(() => {
          return Promise.race(promises); // 返回已经完成的下标
        })
        .then(fastestIndex => { // 获取到已经完成的下标
        	// 将"容器"内已经完成的那一项替换
          promises[fastestIndex] = handler(url).then(
            (res) => {
              div.appendChild(res)//渲染到页面中
              return fastestIndex; // 要继续将这个下标返回,以便下一次变量
            }
          );
        })
        .catch(err => {
          console.error(err);
        });
    }, Promise.resolve()) // 初始化传入
    .then(() => { // 最后三个用.all来调用
      return Promise.all(promises);
    });
}
limitLoad(urls, loadImg, 3)
  .then(res => {
    console.log("图片全部加载完毕");
    console.log(res);

  })
  .catch(err => {
    console.error(err);
  });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一夕ξ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值