Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

javascript - Return Promise result instead of Promise in Nodejs

Background

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

Problem

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

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. 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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...