setTimeout async promise执行顺序总结(转)

settimeout,async,promise混用时,哪一步该执行什么,分不清楚。

话不多说,先上代码(该题为今日头条前端开发笔试题)


    
    
  1. async function async1() {
  2. console.log( “async1 start”);
  3. await async2();
  4. console.log( “async1 end”);
  5. }
  6. async function async2() {
  7. console.log( ‘async2’);
  8. }
  9. console.log( “script start”);
  10. setTimeout( function () {
  11. console.log( “settimeout”);
  12. }, 0);
  13. async1();
  14. new Promise( function (resolve) {
  15. console.log( “promise1”);
  16. resolve();
  17. }).then( function () {
  18. console.log( “promise2”);
  19. });
  20. console.log( ‘script end’);

大家可以看一下,自己思考一下题目的输出结果是什么。

好啦,我们来看答案:


    
    
  1. script start
  2. async1 start
  3. async2
  4. promise1
  5. script end
  6. async1 end
  7. promise2
  8. settimeout

我们来挨个分析一下,

await  async2();//执行这一句后,输出async2后,await会让出当前线程,将后面的代码加到任务队列中,然后继续执行test()函数后面的同步代码
    
    

执行到setTimeout函数时,将其回调函数加入队列(此队列与promise队列不是同一个队列,执行的优先级低于promise)。继续执行

创建promise对象里面的代码属于同步代码,promise的异步性体现在then与catch处,所以promise1被输出,然后将then函数的代码加入队列,继续执行同步代码,输出script end。

至此同步代码执行完毕,开始从队列中调取任务执行,由于刚刚提到过,setTimeout的任务队列优先级低于promise队列,所以首先执行promise队列的第一个任务,即执行async1中await后面的代码,输出async1 end。

然后执行then方法的部分,输出promise2。最后promise队列中任务执行完毕,再执行setTimeout的任务队列,输出settimeout。


至此,该题的输出结果分析完毕了,这类的执行结果可以用一句话总结,先执行同步代码,遇到异步代码就先加入队列,然后按入队的顺序执行异步代码,最后执行setTimeout队列的代码。

补充一下队列任务优先级:promise.Trick()>promise的回调>setTimeout>setImmediate


settimeout,async,promise混用时,哪一步该执行什么,分不清楚。

话不多说,先上代码(该题为今日头条前端开发笔试题)


  
  
  1. async function async1() {
  2. console.log( “async1 start”);
  3. await async2();
  4. console.log( “async1 end”);
  5. }
  6. async function async2() {
  7. console.log( ‘async2’);
  8. }
  9. console.log( “script start”);
  10. setTimeout( function () {
  11. console.log( “settimeout”);
  12. }, 0);
  13. async1();
  14. new Promise( function (resolve) {
  15. console.log( “promise1”);
  16. resolve();
  17. }).then( function () {
  18. console.log( “promise2”);
  19. });
  20. console.log( ‘script end’);

大家可以看一下,自己思考一下题目的输出结果是什么。

好啦,我们来看答案:


  
  
  1. script start
  2. async1 start
  3. async2
  4. promise1
  5. script end
  6. async1 end
  7. promise2
  8. settimeout

我们来挨个分析一下,

await  async2();//执行这一句后,输出async2后,await会让出当前线程,将后面的代码加到任务队列中,然后继续执行test()函数后面的同步代码
  
  

执行到setTimeout函数时,将其回调函数加入队列(此队列与promise队列不是同一个队列,执行的优先级低于promise)。继续执行

创建promise对象里面的代码属于同步代码,promise的异步性体现在then与catch处,所以promise1被输出,然后将then函数的代码加入队列,继续执行同步代码,输出script end。

至此同步代码执行完毕,开始从队列中调取任务执行,由于刚刚提到过,setTimeout的任务队列优先级低于promise队列,所以首先执行promise队列的第一个任务,即执行async1中await后面的代码,输出async1 end。

然后执行then方法的部分,输出promise2。最后promise队列中任务执行完毕,再执行setTimeout的任务队列,输出settimeout。


至此,该题的输出结果分析完毕了,这类的执行结果可以用一句话总结,先执行同步代码,遇到异步代码就先加入队列,然后按入队的顺序执行异步代码,最后执行setTimeout队列的代码。

补充一下队列任务优先级:promise.Trick()>promise的回调>setTimeout>setImmediate


猜你喜欢

转载自blog.csdn.net/qq_28019937/article/details/81948795