How do nested Javascript returns “pass up” promises?

天大地大妈咪最大 提交于 2021-02-11 12:23:14

问题


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.


回答1:


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!"));


来源:https://stackoverflow.com/questions/52107165/how-do-nested-javascript-returns-pass-up-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!