I am working in a framework that requires the parent function to return true or false. Within that function, I'd like to run an async operation.
How do I make the parent function return true or false after an async action?
Example of what doesn't work:
function parent() {
const child = new Promise();
child.then(
function (success) { return true },
)
}
The problem is that returning is happining within the context of the child.then() function.
This necessarily requires that the parent function be async as well, unless you want to block the main thread, which would be considered an anti-pattern.
Do this:
const parent = async () => {
const childResponse = await child();
if (childResponse === "something") {
return true;
} else {
return false;
}
};
Do NOT do this:
const parent = () => {
let promiseResult, parentReturnValue;
child.then(result => {
promiseResult = result;
if (promiseResult === "something") {
parentReturnValue = true;
} else {
parentReturnValue = false;
}
});
while (promiseResult === undefined) {
// block the main thread
}
return parentReturnValue;
};