JS async / await - why wait for async?
Why await
should the external function be declared when using it async
?
For example, why does this mongoose expression need a function where it returns a promise?
async function middleware(hostname, done) {
try {
let team = await Teams.findOne({ hostnames: hostname.toLowerCase() }).exec();
done(null, team);
} catch (err) { done(err); }
}
I can see that the runtime / transporter is resolving the value of the command promise and is signaling asynchronously that it is "discarding" rejected promises.
But try / catch catches these rejected promises, so why are asynchronous and awaiting so tightly coupled?
source to share
I'm not familiar with the discussion of JavaScript language design, but I assume that for the same reasons as C # language is required async
(see also my blog ).
Namely:
- Backward compatibility. If there
await
was a new keyword everywhere, any existing code usingawait
as a variable name would break. Since itawait
is a contextual keyword (activatedasync
), only the code that intends to be usedawait
as a keyword will have aawait
keyword. - Easier to disassemble.
async
makes it easy to parse asynchronous code for transporters, browsers, tools, and people.
source to share
Copied from fooobar.com/questions/188934 / ... @phaux:
All of these answers provide correct arguments for why the async keyword is good, but none of them mention the real reason why it was added to the spec.
The reason is that this was valid pre-ES7 JS
function await(x) { return 'awaiting ' + x } function foo() { return(await(42)) }
As per your logic,
foo()
returnPromise{42}
or"awaiting 42"
? (returning a promise will recede backward compatibility)So the answer is:
await
is a regular identifier and it is only treated as a keyword inside async functions, so they need to be tagged in some way.Fun fact: the original specification offered an easier
function^ foo() {}
syntax for asynchronous programming.
source to share