what is the difference if a normal method or async method is called on an object ?
(1) myObject.handleUpdate() // conventional method
(2) myObject.handleUpdate() // handleUpdate is declared async
I know that async methods return always promise. But apart from that. Does async method run in a separate thread ? And what does it mean if an async method is called in a test framework. You need to wait for it ? In contrast a normal method (1) is called in the same thread you can call it without any hooks in a test framework
2
Answers
If you worked with promises, you know that async calculations are synced up again by placing the subsequent one inside the callback of the
.then(…)
method of the Promise instance of the original one.The
await
keyword is a syntax sugar that does exactly that under the hood, — just a nicer syntax for something that would otherwise require a chain of.then(…)
calls.The
async
keyword allows using theawait
keyword immediately inside of the async function body.There really isn’t much more of a difference. For example, there is no way of providing the callback for
.catch(…)
, you have to wrap the calculation intry..catch
block.That’s basically it. It always returns a promise, and allows use of the
await
keyword inside the function. A return statement in the async function will cause the promise to resolve with that value. A throw statement in the async function will cause the promise to reject.No.
Yes, probably. In most cases, your test will care about when the promise resolves. To find out when that happens, you will need to
await
the promise (or call.then
on it). If for some reason you don’t care about when the promise resolves then you don’t need to await it, but that’s less common.