I started to use ES7 feature async/await
, which gives the best approach to deal with asynchronous tasks, and makes your code cleaner and readable.
However it doesn't give you an access to Promise, created by async function, so if you do some async request in your async function you should promisify it, then await it and then return the result. I mean this:
async function doStuff() {
//stuff...
var value = await new Promise(function(resolve) {
$.get('http://some/url/...', function(result) {
// stuff...
resolve(result);
});
});
return value;
}
What if you could find a pointer to the Promise created by function so your code could look like:
async function doStuff() {
//stuff...
var p = arguments.callee.promise;
$.get('http://some/url/...', function(result) {
// stuff...
p.resolve(result);
});
}
or even:
async function doStuff() {
//stuff...
$.get('http://some/url/...', function(result) {
// stuff...
async.resolve(result);
});
}
This way you don't need to directly access Promises API what makes your code totally focused on task without any besides.
async
/await
. Can you produce a scenario where simply doingresult = await $.get(someUrl); doStuffWith(result)
is not sufficient? The whole point of the proposal is not to have to deal with callbacks. – Hoist