返回 Promise 结果而不是 Nodejs 中的 Promise [英] Return Promise result instead of Promise in Nodejs

查看:33
本文介绍了返回 Promise 结果而不是 Nodejs 中的 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 Promise,并且我有一个想要改进的 Promise 链.

I am trying to learn promises, and I have a promise chain I want to improve on.

在学习如何链接 promise 时,我不明白为什么有人宁愿返回 promise 而不是返回它的值.

While learning how to chain promises, I fail to see why anyone would rather return a promise instead of returning it's value.

以下面的例子为例,它使用了承诺链:

Take the following example, which uses promise chaining:

let myObj = new MyClass();

myObj.getInfo()
    .then(result => writeOutput(FILE_NAME, result))
    .then(console.log(FILE_NAME + " complete"))
    .catch(error => console.error(error));

class MyClass{

    getInfo() {
        return new Promise(function(fulfil, reject) {
            fulfill("I like bananas");
        });
}

这里我必须链接 2 次.但是,如果我直接从 getInfo() 方法返回结果而不是返回 Promise,我可能会执行以下操作:

Here I have to chain 2 times. But if I were to directly return the result from the method getInfo() instead of returning a Promise I could potentially do something like the following:

let myObj = new MyClass();

let str = myObj.getInfo();

writeOutput(FILE_NAME, str)
    .then(console.log(FILE_NAME + " complete"))
    .catch(error => console.error(error));

问题

如你所见,我有点困惑.

Questions

So as you can see I am a little confused.

  1. 鉴于 getInfo() 实际上是异步的,是否可以实现与我的第二个代码示例中的代码类似的代码?
  2. 如果可能,这是个好主意吗?你会怎么做?
  1. Given that getInfo() is in fact async, is it possible to achieve a similar code to the one in my second code sample?
  2. If it were possible, would it be a good idea? How would you do it?

推荐答案

您只能从某个函数返回一个值,如果该值在调用该函数时立即可用(在事件循环的同一滴答上).请记住,return 是同步的.

You can only return a value from some function if that value is immediately available when that function is called (on the same tick of the event loop). Remember that return is synchronous.

如果它不能立即可用,那么您只能返回一个承诺(或者您可以使用回调,但在这里您专门询问承诺).

If it is not available right away then you can only return a promise (or you can use a callback but here you are specifically asking about promises).

有关更详细的解释,请参阅我前段时间写的关于如何从某个函数返回 AJAX 调用结果的问题的答案.我解释了为什么你不能返回值但你可以返回一个承诺:

For a more detailed explanation see this answer that I wrote some time ago to a question asking on how to return a result of an AJAX call from some function. I explained why you cannot return the value but you can return a promise:

这是另一个相关的答案 - 由于某种原因它被否决了,但我认为它解释了你问她的类似问题:

Here is another related answer - it got downvoted for some reason but I think it explains a similar issue that you're asking about her:

这篇关于返回 Promise 结果而不是 Nodejs 中的 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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