0

I can't wrap my head around this.

Take the following three functions where a calls b, and b calls c:

const c = () => {
    return new Promise( (resolve, reject) => {
        setTimeout(() => {
            resolve(new Date());
        }, "1750");
    });
};

const b = async () => {
    const result = await c();
    console.log("b(): %s", result);
    return result;
};

const a = async () => {
    const result = await b();
    console.log("a(): %s",result);
    return result;
};

console.log("Starting...");
const final_result = a();
console.log("Final Result: %s", final_result);
console.log("Ending...");

I expected b() to wait-for/get the result of the promise returned by c(), and pass the value to a(). However, it looks like the promise gets passed all the way up the call stack.

enter image description here

To get the behavior I want, I have to handle the promise in each function:

const c = () => {
    return new Promise( (resolve, reject) => {
        setTimeout(() => {
            resolve(new Date());
        }, "1750");
    });
};

const b = async () => {
    const result = await c();
    console.log("b(): %s", result);
    return result;
};

const a = async () => {
    const result = await b();
    console.log("a(): %s",result);
    return result;
};
(async () => {
    console.log("Starting...");
    const final_result = await a();
    console.log("Final Result: %s", final_result);
    console.log("Ending...");
})()

enter image description here

Why can't I just get the result of the promise in one function and return that? And, if I can do it, how?

Adam
  • 3,891
  • 3
  • 19
  • 42
  • So basically you want to return a value from an async function? You want the value and not a promise – Patrick Hollweck Oct 03 '19 at 18:25
  • Yes!! @PatrickHollweck you understand me!! – Adam Oct 03 '19 at 18:26
  • 1
    You can not do that, That is not possible. Once you make something async there is no way to make it sync again.[Read this relevant existing question :)](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323) Is there a reason for why you cant handle/await the promise? – Patrick Hollweck Oct 03 '19 at 18:27
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Patrick Hollweck Oct 03 '19 at 18:48

0 Answers0