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?

+9


source to share


2 answers


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:



  1. Backward compatibility. If there await

    was a new keyword everywhere, any existing code using await

    as a variable name would break. Since it await

    is a contextual keyword (activated async

    ), only the code that intends to be used await

    as a keyword will have a await

    keyword.
  2. Easier to disassemble. async

    makes it easy to parse asynchronous code for transporters, browsers, tools, and people.
+6


source


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()

return Promise{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.

+4


source







All Articles