Search code examples
javascriptfunctionasynchronouspromisees6-promise

How do nested Javascript returns "pass up" promises?


This question has two parts, both relating to how Javascript promises are passed around functions using return statements.

1)

I have simple Javascript function, which includes multiple return statements. The inner function returns a promise to an arrow function, the arrow function is also returned, like this:

const returnMe(data){
  return () => {
    return Promise.resolve(data);
  };
};

Could I write the following code?

returnMe("Hello!").then((msg) => { console.log(msg) }); /// --> output "Hello!" ??

In other words, if a nested function receives a resolved/rejected promise, and that function is returned to it's parent function, does the parent function receive the resolved/rejected promise?

2)

Another, related but somewhat different example....

 const returnMe(data){
    return () => {
      return Promise.resolve(data).then(() => { console.log("Ha!") });
    };
 };

In this case, the "then" call happens inside the function. Does the then call "use up" the promise? In this case, what is returned to the arrow function, and then to the parent function?

Thank you for your help.


Solution

  • 1) Since returnMe() returns a function, you have to call that function. That will return a promise, which you can then use with .then()

    function returnMe(data){
      return () => {
        return Promise.resolve(data);
      };
    };
    
    returnMe("Hello!")().then(msg => console.log(msg));

    2) The inner .then() consumes the data that the promise resolves to, but it returns a new promise. So you can call .then() on this.

    As with example 1, you need to call the function that returnMe() returns in order to execute the inner function.

    function returnMe(data){
        return () => {
          return Promise.resolve(data).then(() => { console.log("Ha!") });
        };
     };
     
     returnMe("Hello!")().then(() => console.log("Done!"));