嵌套Javascript如何返回“传递"消息.承诺? [英] How do nested Javascript returns "pass up" promises?

查看:51
本文介绍了嵌套Javascript如何返回“传递"消息.承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题分为两个部分,都与如何使用return语句在函数周围传递Javascript承诺有关.

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

1)

1)

我有简单的Javascript函数,其中包括多个return语句.内部函数向箭头函数返回一个promise,箭头函数也被返回,如下所示:

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!" ??

换句话说,如果嵌套函数收到已解决/已拒绝的诺言,并且该函数返回给它的父函数,那么父函数会收到已解决/已拒绝的诺言吗?

2)

2)

另一个相关但又有些不同的示例....

Another, related but somewhat different example....

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

在这种情况下,"then"调用发生在函数内部.然后调用用完"诺言吗?在这种情况下,返回箭头功能然后返回父功能的内容是什么?

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?

谢谢您的帮助.

推荐答案

1)由于 returnMe()返回一个函数,因此必须调用该函数.这将返回一个承诺,然后您可以将其与 .then()

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)内部的 .then()消耗了承诺解析的数据,但它返回了一个新的承诺.因此,您可以对此调用 .then().

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.

与示例1一样,您需要调用 returnMe()返回的函数以执行内部函数.

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

这篇关于嵌套Javascript如何返回“传递"消息.承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆