Is it possible to resolve async function without return keyword
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
});
});
}
When you're returning a promise from a function there is no need for the function to be async, actually it's even bad because you are creating two promise!
function doStuff() {
return new Promise(function(resolve, reject) {
$.get('http://some/url/...', result => resolve(result));
});
}
async function main() {
const result = await doStuff();
}