Any difference between “await Task.Run(); return;” and “return Task.Run()”?

One major difference is in exception propagation. An exception, thrown inside an async Task method, gets stored in the returned Task object and remains dormant until the task gets observed via await task, task.Wait(), task.Result or task.GetAwaiter().GetResult(). It is propagated this way even if thrown from the synchronous part of the async method. Consider the … Read more

Waiting for more than one concurrent await operation

TL;DR Don’t use the pattern in the question where you get the promises, and then separately wait on them; instead, use Promise.all (at least for now): const [value1, value2] = await Promise.all([getValue1Async(), getValue2Async()]); While your solution does run the two operations in parallel, it doesn’t handle rejection properly if both promises reject. Details: Your solution … Read more

Correct Try…Catch Syntax Using Async/Await

It seems to be best practice not to place multiple lines of business logic in the try body Actually I’d say it is. You usually want to catch all exceptions from working with the value: try { const createdUser = await this.User.create(userInfo); console.log(createdUser) // business logic goes here } catch (error) { console.error(error) // from … Read more

Combination of async function + await + setTimeout

Your sleep function does not work because setTimeout does not (yet?) return a promise that could be awaited. You will need to promisify it manually: function timeout(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function sleep(fn, …args) { await timeout(3000); return fn(…args); } Btw, to slow down your loop you probably don’t want … Read more

Async function returning promise, instead of value

Async prefix is a kind of wrapper for Promises. async function latestTime() { const bl = await web3.eth.getBlock(‘latest’); console.log(bl.timestamp); // Returns a primitive console.log(typeof bl.timestamp.then == ‘function’); //Returns false – not a promise return bl.timestamp; } Is the same as function latestTime() { return new Promise(function(resolve,success){ const bl = web3.eth.getBlock(‘latest’); bl.then(function(result){ console.log(result.timestamp); // Returns a … Read more

How would I run an async Task method synchronously?

Here’s a workaround I found that works for all cases (including suspended dispatchers). It’s not my code and I’m still working to fully understand it, but it does work. It can be called using: customerList = AsyncHelpers.RunSync<List<Customer>>(() => GetCustomers()); Code is from here public static class AsyncHelpers { /// <summary> /// Execute’s an async Task<T> … Read more