function promiseDelay(miliseconds) { return new Promise((resolve) => { setTimeout(resolve, miliseconds)})}
To use this function to delay your call, just place the logic inside .then() method
promiseDelay(1000).then(() => {console.log('hello')})
When there's a list of values to be processed, we can keep chaining new deplayPromise at the end of the promise:
This is a little hard to read, as there is .then() inside a .then(). Note that the next execution is not depending on the result of the delay, this is equivalent to wrap the execution into another promise, and use Promise.all() to ensure both delay and execution to be both completed before proceeding:
p = Promise.resolve(undefined) [1,2,3].forEach(x=> { p = p.then(() => promiseDelay(1000).then(() => {console.log(x)}) ) })
function promiseDisplay(x) { return new Promise((resolve) => { console.log(x); resolve()}) } Promise.all([promiseDelay(1000), promiseDisplay(x)]);
Applying the above change, the code now looks nice: