0

I just started working with Promise objects in JS and I can't figure out something.

I need to create a function that receives a Promise object as parameter, if the promise is resolved I need to return a success object, otherwise an empty Error object. But it seems to not be returning anything.

export default function handleResponseFromAPI(promise) {
    promise.then(() => {
        console.log('Got a response from the API');
        return { status: 200, body: 'Success' };
    }, () => {
        console.log('Got a response from the API');
        return new Error();
    });
}

And I call it here:

import handleResponseFromAPI from "./2-then";

const promise = Promise.resolve();
const returnObject = handleResponseFromAPI(promise);
console.log(returnObject);

What shows up on console:

undefined
Got a response from the API

I can see that first it returns undefined and then prints the message from my function. Anyone cares to explain the process of this?

  • Your function does not return anything, so it returns `undefined` implicitly. If you want it to return the object, you must use `async`/`await` which you can find [here](https://javascript.info/async-await). – kelsny Apr 12 '22 at 15:19
  • `handleResponseFromAPI` does not itself return anything. It's just appending callbacks to the promise. It can return the promise itself, though if all you're doing is appending callbacks then your test already confirms that it successfully does that without needing to return anything. In the consuming code you can still `await` the `promise` object, or append a `.then()` callback to it. If you want to return the `promise` from the function then `returnObject` will just be that same `promise` again, so there's little value in doing that. – David Apr 12 '22 at 15:23

0 Answers0