-1

Similar to this question Java Equivalent of C# async/await? which asked about Java, I am asking about Javascript.

How do I write the following C# in Javascript in an async /await manner, without using callbacks

public async Task<IHttpActionResult> SomeMethod(string myStr) {
  await Task.Delay(2000);

  //== continue here after 2 secs
}
Derek Wang
  • 10,098
  • 4
  • 18
  • 39
joedotnot
  • 4,810
  • 8
  • 59
  • 91
  • according to https://stackoverflow.com/questions/5449956/how-to-add-a-delay-for-a-2-or-3-seconds this does not block the main thread like the `async / await` in javascript. i would say yes, they are pretty the same – bill.gates Oct 19 '20 at 07:48
  • @Ivar yes i like the one liner: await new Promise(r => setTimeout(r, 2000)); – joedotnot Oct 19 '20 at 08:22

1 Answers1

2

You could write your own delay method.

function delay(time) {
    return new Promise((resolve) => {
        setTimeout(() => resolve(), time);
    });
}

To use it

async function someMethod(myStr) {
    await delay(2000);

    // Continue here after 2 secs
}
Mathyn
  • 2,436
  • 2
  • 21
  • 33
  • 3
    Ok, as suggested by another link above, there is a one liner await new Promise(r => setTimeout(r, 2000)); – joedotnot Oct 19 '20 at 08:23