这段代码如何改写为promise形式的?

var count = 0;

setTimeout(function(){
  console.log("step1", count);
  count += 1;
  setTimeout(function(){
    console.log("step2", count);
    count += 1;
    setTimeout(function(){
      console.log("step3", count);
      count += 1;
      setTimeout(function(){
        console.log("step4", count);
        count += 1;
        setTimeout(function(){
          console.log("step5", count);
          count += 1;
          setTimeout(function(){
            console.log("step6", count);
            count += 1;
          }, 1000);
        }, 1000);
      }, 1000);
    }, 1000);
  }, 1000);
}, 1000);
阅读 3.4k
2 个回答

这么写?

'use strict';

var timer = function(cb, ms) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            cb();
            resolve();
        }, ms);
    });
};

var count = 0;

timer(function() {
    console.log('step1', count);
    count += 1;
}, 1000)
.then(function() {
    return timer(function() {
        console.log('step2', count);
        count += 1;
    }, 1000);
})
.then(function() {
    return timer(function() {
        console.log('step3', count);
        count += 1;
    }, 1000);
})
.then(function() {
    return timer(function() {
        console.log('step4', count);
        count += 1;
    }, 1000);
})
.then(function() {
    return timer(function() {
        console.log('step5', count);
        count += 1;
    }, 1000);
})
.then(function() {
    return timer(function() {
        console.log('step6', count);
        count += 1;
    }, 1000);
});

如果涉及到变量复用的话用 Promise 可能还稍微麻烦一点,这时候用 async/await 绝对是上乘之举了,在线运行:http://goo.gl/fb29D3

step_by_step就是你要的 Promise 版,后面是配合 async/await 的使用方法。

function step_by_step(count) {
  return new Promise(function(resolve) {
    setTimeout(function(){
      count += 1;
      resolve(count);
    }, 1000);
  });
}

(async function main() {
  let count = 0;
  for(let i=0;i<6;i++) {
    count = await step_by_step(count);
    console.log(`step${count}`, count);
  }
})();

当然直接用 Promise 去写也是可以的,使用外部变量存储后即可,然而两相对比之下,怎么看都还是 async/await 写起来更加优雅呢。

var count = 0;
step_by_step(count).then(function(count){
    console.log(count);
    return step_by_step(count);
}).then(function(count){
    console.log(count);
    return step_by_step(count);
}).then(function(count){
    console.log(count);
    return step_by_step(count);
}).then(function(count){
    console.log(count);
    return step_by_step(count);
}).then(function(count){
    console.log(count);
    return step_by_step(count);
}).then(function(count){
    console.log(count);
    return step_by_step(count);
}).then(function(count){
    console.log(count);
    return step_by_step(count);
});

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题