Simulating async await in javascript

Tech:
Javascript
Since:
1 year ago
Views:
6

Sometimes we may need to simulate async/await locally for testing purposes instead of calling the actual API.

new Promise with setTimeout

async function simulateAsync() {
  await new Promise(resolve => setTimeout(resolve, 5000));
  return "simulatedAsyncAwait";
}

(async function() {
  var response = await simulateAsync();
  console.log(response);
})();

Output:

// After 5 seconds, output would be

simulatedAsyncAwait