在javascript中的另一个setTimeout函数中使用setTimeout

时间:2018-04-12 11:47:36

标签: javascript node.js socket.io mean-stack async.js

我有这个代码: -

    var i = 3
    var p = Promise.resolve(i)
    while (i > 0) {
      (i => {
        p = p.then(() => {
          return new Promise(function (resolve, reject) {
            console.log('start', i)        
            setTimeout(function () {
              setTimeout(() => {
                console.log('timeout')
              }, 1000);
              console.log('end', i)
              resolve()
            }, 1000)
          })
        })
      })(i)
      i--
    }
    p = p.then(data => console.log('execution ends'))

我的输出是这样的: -

start 3
end 3
start 2
timeout
end 2
start 1
timeout
end 1
execution ends
timeout

但是,我的预期输出应该是这样的: -

start3
timeout
end3
start2
timeout
end2
start1
timeout
end1

简而言之,因为我的预期输出'超时'日志应该每2秒打印一次,其他日志应该每1秒打印一次。

2 个答案:

答案 0 :(得分:1)

试试这个:



var i = 3
var p = Promise.resolve(i)
while (i > 0) {
  (i => {
    p = p.then(() => {
      return new Promise((resolve) => {
        console.log('start', i)
        setTimeout(() => {
          return new Promise((resolve) => {
            setTimeout(() => {
          	console.log('timeout')
            	resolve()
            }, 1000)
          }).then(() => {
          	console.log('end', i)
          	resolve()
          })
        }, 1000)
      })
    })
  })(i)
  i--
}
p = p.then(data => console.log('execution ends'))




我所做的是为记录timeout的新超时添加一个新的Promise,因此只有在完成此操作后它才会继续。

答案 1 :(得分:0)

以下是否正确执行?



const later = time => value =>
  new Promise(
    resolve=>
      setTimeout(() => {
        resolve(value)
      }, time)
  );
const afterOneSecond = later(1000);
Array.from(new Array(3),(i,index)=>3-index)
.reduce(
  (promise,value)=>
    promise.then(afterOneSecond)
    .then(()=>console.log("start:",value))
    .then(afterOneSecond)
    .then(()=>console.log("timeout"))
    .then(()=>console.log("end:",value)),
  Promise.resolve()
)
.then(() => console.log('execution ends'));