I have this case below (for simplicity, the functions has no, or a little bit of, content):
async someAsyncStuff() {
let result = await stuffToDo()
return result
}
functionThatCannotBeAsync() {
someAsyncStuff()
// wait for the above to finish
// return with result
}
Now for system-wise reasons, functionThatCannotBeAsync() cannot be async and therefore cannot use await someAsyncStuff(), but it still needs to call it, wait for it to finish, and then return with its result.
I've tried to come up with something like this:
async someAsyncStuff(res, callback) {
let result = await stuffToDo()
res.result = result
callback()
return result
}
functionThatCannotBeAsync() {
let done = false
let result = {result: ""}
someAsyncStuff(result, () => { done = true })
while(!done) {}
return result.result
}
My logic says that functionThatCannotBeAsync() should've waited in the while loop, and eventually done will become true and the function will return with the desired value. In actual, the while loop lasts forever.
Can someone please explain to me why this is happening? What is the correct way to do it (except for async\await, which I cannot use here).
Thanks in advance
CodePudding user response:
You can implicitly return a Promise. Like so:
/* To implement a function that fetches from an endpoint and returns a promise of the result without using `async`/`await` syntax
*/
function functionThatCannotBeAsync(url) {
return new Promise(resolve => {
fetch(url)
.then(response => response.json())
.then(jsonResponse => resolve(jsonResponse));
})
}
const clientFunction = async () => {
const apiResponse = await functionThatCannotBeAsync("http://api.plos.org/search?q=title:DNA");
console.log("response: ", apiResponse);
}
clientFunction();
CodePudding user response:
You can use an immediately invoked anonymous expression, IIFE, to convert your async function to sync.
An async IIFE allows you to use await and for-await even in older browsers and JavaScript runtimes that have no top-level await:
This is assuming you don't need to do anything between the time you call the IIFE and its return
functionThatCannotBeAsync() {
(async () => await someAsyncStuff())()
// wait for the above to finish
// return with result
}