I have a parent function that calls a child function.
The child function will execute its internal code asynchronously so I'd like the parent function to call the child and then continue its own execution without waiting.
function childFunc() {
axios.post("http://api.example.com/user", { foo: "bar } ).
then((response) => {
// Do stuff here
console.log("SUCCESS");
return [1, 2, 3];
}).
catch((err) => {
// Do stuff here
console.log("ERROR");
return [];
});
console.log("About to return null");
}
function parentFunc(url, data) {
// Call childFunc but then continue execution
new Promise(function(resolve, reject) {
let result = childFunc(url, data);
result.length > 0 ? resolve(result) : reject("some error");
});
console.log("Continuing execution of `parentFunc()`");
// Continue doing other stuff
}
I'm just learning about Promise
and async
behavior in JavaScript, so I'm confused about the following:
What will
childFunc
return? Ifaxios.post
is executed asynchronously, wont the execution always continue past that and returnnull
? Will thereturn
statements insidethen()
orcatch()
ever fire? Does it return something twice?Will the logic in
parentFunc
do what I expect it to do here: callchildFunc
asynchronously while simultaneously moving forward with its own execution? I've seen theasync/await
syntax, but wasn't sure how that really worked and whether that could be used here somehow.
Thanks!