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.
Is it possible to resolve async function without return keyword
No.
There is no way to get a reference to the promise that the call to the async function
created, but there really is no need to access that either (and btw, you cannot .resolve()
a promise, you'd actually need to get access to the promise's resolving functions).
The whole point of async
/await
is to play nice with promises and other thenables. The idea is that every asynchronous function returns a promise, and that you don't have to promisify anything (but if you really have to, do it separately) - and in fact, $.get
does return a (jQuery) promise. So simply write
async function doStuff() {
//stuff...
var result = await $.get('http://some/url/...');
// stuff...
return someValue;
}
If you really have a callback-taking function, use a simple
async function doStuff() {
// stuff…
return new Promise(function(resolve, reject) {
$.get({
url: 'http://some/url/...',
success: resolve,
error: reject
// don't do other "stuff" in here
});
});
}