A message on the topic of Async/Await

24 views
Skip to first unread message

Popey Gilbert

unread,
Feb 25, 2017, 7:25:29 PM2/25/17
to nodejs
Hello guys,

It strikes me as an interesting development to see that the current definition of Async/Await (as I see it), is as simple syntactic sugar for .then().  While I, to an extent, see the point of such a command as being useful, I remain unaware of the exact reasoning why we need to include promises in the first place.  Wouldn't it be so much more powerful to be able to use completely normal syntax, as you would in synchronous code, instead of the awkwardness of Promises?

For example, take the following code snippet:

function asyncFunction() {
  return new Promise((resolve, reject) => {
    someAsync('data', (err, data) => {
      if (err) {
        reject(err); return;
      }
      resolve(data);
    });
  }); 
}

This seems to be so very confusing for anybody new studying this language, almost everyone I talk to gets stuck up on some part of it.  Wouldn't it be so very beautiful if we could just do:

function asyncFunction() {
	someAsync('data', (err, data) => {
		return [err, data]
	})
}

When we call this with the `await` keyword, we simply `await` a return.  No special promises or extra keywords needed, everything works as you would expect it to.

async function asyncFunction() {
	let [err, data] = await asyncFunction()
}

Honestly, are we just making life complicated for ourselves with utilising promises & await/async?  

Zlatko

unread,
Feb 26, 2017, 1:12:20 PM2/26/17
to nodejs
The answer is super simple and it's actually a question. Let's say we have your last asyncFunction and the stuff works as you propose, without the Promise past.

Which of the function's two return statements should I wait for? The outer one (which returns undefined) out that inner one from callback? Furthermore, what if you had two async calls in there, nested our sequential it's irrelevant. Which one to await then?
Add a setTimeout inside. What now?
We use promise so that the caller of the async code knows exactly when we resolve the value. We use await to sugar it a bit. I hope that helps highlight the problem a little.
Reply all
Reply to author
Forward
0 new messages