promise与setTimeout 判断执行顺序

promise和setTimeout都会将事件放入异步队列,但setTimeout即便是写0,也会有4ms的延迟

console.log('begin');

setTimeout(() => {

  console.log('setTimeout 1');

  Promise.resolve()
    .then(() => {
      console.log('promise 1');
      setTimeout(() => {
          console.log('setTimeout2');
      });
    })
    .then(() => {
      console.log('promise 2');
    });

  new Promise(resolve => {
    console.log('a');
    resolve();
  }).then(() => {
    console.log('b');
  });

}, 0);
console.log('end');

答案

begin
end
setTimeout 1
a
promise 1
b
promise 2
setTimeout2

async函数的使用

function repeat(func, times, wait) {

}
// 输入
const repeatFunc = repeat(alert, 4, 3000);

// 输出
// 会alert4次 helloworld, 每次间隔3秒
repeatFunc('hellworld');
// 会alert4次 worldhellp, 每次间隔3秒
repeatFunc('worldhello')

我自己的实现,没有成功。这种实现是setTimeout新建了两个,然而只清理了一个。

function repeat(func, times, wait) {
  var timer = null;
  var count = 0;
  return function(...args) {
    timer = setInterval(function() {
      func.apply(null, args);
      count ++;
      console.log('count', count, "times", times)
      if( count >= times) {
        clearInterval(timer);
      }
    }, wait);
  }
}
// 输入
const repeatFunc = repeat(console.log, 4, 3000);
// 输出
// 会alert4次 helloworld, 每次间隔3秒
repeatFunc('hellworld');
// 会alert4次 worldhellp, 每次间隔3秒
repeatFunc('worldhello');

正确解法:使用 async/await来实现

async function wait(seconds) {
    return new Promise((res) => {
        setTimeout(res, seconds);
    });
}

function repeat(func, times, s) {
    return async function (...args) {
        for (let i = 0; i < times; i++) {
            func.apply(null, args);
            await wait(s);
        }
    };
}

let log = console.log
let repeatFunc = repeat(log,4,3000)
repeatFunc('HelloWorld')
repeatFunc('WorldHello')

async执行练习

  • await后面的才是异步的,之前都是同步的
async function async1() {
  console.log('async1 start');  // 2
  await async2();
  console.log('async1 end');    // 6
}

async function async2() {     
  console.log('async2');        // 3
}

console.log('script start');    //  1

setTimeout(function() {
  console.log('setTimeout');    // 8
}, 0);

async1();

new Promise(function(resolve) {
  console.log('promise1');      // 4
    resolve();
  }).then(function() {
      console.log('promise2');  // 7
  });

console.log('script end');      // 5

看代码,写结果

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')

解题思路

results matching ""

    No results matching ""