Skip to content Skip to sidebar Skip to footer

How To Make An Async Then?

Basically I am trying to play around to understand more of async/await and promise in JS. I'm trying to make Hello comes in between finished! and third finish!!. So the best guess

Solution 1:

You need the second section to be a Promise, and return it from the .then so that it's properly chained between the first and the third. setTimeout doesn't return a Promise, you have to explicitly construct a Promise instead:

let promise = newPromise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(() => {
  returnnewPromise(resolve => {
    setTimeout(function(){     
      console.log("Hello");
      resolve();
    }, 1000);
  });
}).then(() => {
  console.log('third finish!!')
})

Or, using await, use await new Promise followed by the same Promise construction and the setTimeout:

let promise = newPromise((res, rej) => {
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(async() => {
  awaitnewPromise(resolve => {
    setTimeout(function() {
      console.log("Hello");
      resolve();
    }, 1000);
  });
}).then(() => {
  console.log('third finish!!')
})

Solution 2:

Another approach is to write an asynchronous setAsyncTimeout function (this hasn't been thoroughly tested, may need tweaks):

asyncfunctionsetAsyncTimeout(callback, interval) {
    returnnewPromise( (resolve, reject) => {
        setTimeout(() => {
            try {
                let inner = callback()
                if (inner && inner.then) {
                    inner.then(resolve, reject)
                } else {
                    resolve(inner)
                }
            } catch(e) {
                reject(e)
            }
        }, interval)
    })
}

Testing via your example:

let promise = newPromise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then( setAsyncTimeout(function(){     
    console.log("Hello"); }, 3000); 
}).then(() => {
  console.log('third finish!!')
})

Testing via your example (with another promise):

let promise = newPromise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(async () => { //async/await at thenlevelawaitsetAsyncTimeout(function(){     
    console.log("Hello");
    returnsetAsyncTimeout(() =>console.log("world"), 3000)
  }, 3000); 
}).then(() => {
  console.log('third finish!!')
})

Cleaner example:

let promise = newPromise((res,rej)=>{
  res();
});

promise.then(() => {
  console.log('finished!')
}).then(() => {
  returnsetAsyncTimeout(() => { console.log("Hello"); }, 3000)
}).then(() => {
  console.log('third finish!!')
})

Post a Comment for "How To Make An Async Then?"