-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
  • 9,675
  • 4
  • 14
  • 36
joedotnot
  • 4,295
  • 6
  • 49
  • 76
  • 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 – Ifaruki 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

0

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
  • 1,943
  • 1
  • 17
  • 26
  • 1
    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