-3

I'm having this code :-

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

And I got output like this :-

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

but, My expected output should be like this :-

start3
timeout
end3
start2
timeout
end2
start1
timeout
end1

In short, as my expected output 'timeout' log should be print after every 2 seconds and other logs should be print after every 1 second.

Ketan Bodarya
  • 21
  • 1
  • 7
  • you can add the time in your expected output.I am not clear about the interval.See the timestamp in the first demo? – xianshenglu Apr 12 '18 at 11:56
  • Your question is a bit unclear. Also * My expected output will look like* is the same as output of current code. Please check and update question for more clarity – Rajesh Apr 12 '18 at 11:56

2 Answers2

1

Try this:

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

What I did was add a new Promise to a new timeout for logging timeout so it will continue only after this is done.

0

Does the following do it correctly?

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'));
HMR
  • 37,593
  • 24
  • 91
  • 160