Promise function do I need use return?










0















I'm trying to learn pomise and I used code which I found in Internet... I don't understand everything. It looks for me very nasty but it works...



I initialized promise



function initialize(city) 
var options =
url: 'https://api.weatherbit.io/v2.0//forecast/',
headers:
'User-Agent': 'request'

;

return new Promise(function(resolve, reject)
request.get(options, function(err, resp, body)
if (err)
reject(err);
else
resolve(JSON.parse(body));

)
)



I don't understand why I need to put return after initializePromise. Is it possible to refactor the code without return?



 var initializePromise = initialize("Berlin");
return initializePromise.then(function(result)
weather = result;

var rain = result["data"][0]["precip"];
console.log(rain);

, function(err)
console.log(err);
)









share|improve this question

















  • 2





    depends.... is it in a function that needs to return something?

    – epascarello
    Nov 12 '18 at 15:52











  • I need to get data from request function which is calling API

    – Anna K
    Nov 12 '18 at 15:52






  • 1





    Have you tried it? Does it change anything?

    – Nico Haase
    Nov 12 '18 at 15:52






  • 1





    What is the context for the second block of code you give? Is it inside a function which itself needs to return a promise? If you, then, yes, you would need return.

    – Jason Campbell
    Nov 12 '18 at 15:54







  • 2





    @LostJon: This is part of the Promise syntax. While there are some advantages to the .catch() syntax, nothing is wrong with passing the onRejected handler into then.

    – Scott Sauyet
    Nov 12 '18 at 16:29















0















I'm trying to learn pomise and I used code which I found in Internet... I don't understand everything. It looks for me very nasty but it works...



I initialized promise



function initialize(city) 
var options =
url: 'https://api.weatherbit.io/v2.0//forecast/',
headers:
'User-Agent': 'request'

;

return new Promise(function(resolve, reject)
request.get(options, function(err, resp, body)
if (err)
reject(err);
else
resolve(JSON.parse(body));

)
)



I don't understand why I need to put return after initializePromise. Is it possible to refactor the code without return?



 var initializePromise = initialize("Berlin");
return initializePromise.then(function(result)
weather = result;

var rain = result["data"][0]["precip"];
console.log(rain);

, function(err)
console.log(err);
)









share|improve this question

















  • 2





    depends.... is it in a function that needs to return something?

    – epascarello
    Nov 12 '18 at 15:52











  • I need to get data from request function which is calling API

    – Anna K
    Nov 12 '18 at 15:52






  • 1





    Have you tried it? Does it change anything?

    – Nico Haase
    Nov 12 '18 at 15:52






  • 1





    What is the context for the second block of code you give? Is it inside a function which itself needs to return a promise? If you, then, yes, you would need return.

    – Jason Campbell
    Nov 12 '18 at 15:54







  • 2





    @LostJon: This is part of the Promise syntax. While there are some advantages to the .catch() syntax, nothing is wrong with passing the onRejected handler into then.

    – Scott Sauyet
    Nov 12 '18 at 16:29













0












0








0








I'm trying to learn pomise and I used code which I found in Internet... I don't understand everything. It looks for me very nasty but it works...



I initialized promise



function initialize(city) 
var options =
url: 'https://api.weatherbit.io/v2.0//forecast/',
headers:
'User-Agent': 'request'

;

return new Promise(function(resolve, reject)
request.get(options, function(err, resp, body)
if (err)
reject(err);
else
resolve(JSON.parse(body));

)
)



I don't understand why I need to put return after initializePromise. Is it possible to refactor the code without return?



 var initializePromise = initialize("Berlin");
return initializePromise.then(function(result)
weather = result;

var rain = result["data"][0]["precip"];
console.log(rain);

, function(err)
console.log(err);
)









share|improve this question














I'm trying to learn pomise and I used code which I found in Internet... I don't understand everything. It looks for me very nasty but it works...



I initialized promise



function initialize(city) 
var options =
url: 'https://api.weatherbit.io/v2.0//forecast/',
headers:
'User-Agent': 'request'

;

return new Promise(function(resolve, reject)
request.get(options, function(err, resp, body)
if (err)
reject(err);
else
resolve(JSON.parse(body));

)
)



I don't understand why I need to put return after initializePromise. Is it possible to refactor the code without return?



 var initializePromise = initialize("Berlin");
return initializePromise.then(function(result)
weather = result;

var rain = result["data"][0]["precip"];
console.log(rain);

, function(err)
console.log(err);
)






javascript node.js promise






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 12 '18 at 15:50









Anna KAnna K

5231922




5231922







  • 2





    depends.... is it in a function that needs to return something?

    – epascarello
    Nov 12 '18 at 15:52











  • I need to get data from request function which is calling API

    – Anna K
    Nov 12 '18 at 15:52






  • 1





    Have you tried it? Does it change anything?

    – Nico Haase
    Nov 12 '18 at 15:52






  • 1





    What is the context for the second block of code you give? Is it inside a function which itself needs to return a promise? If you, then, yes, you would need return.

    – Jason Campbell
    Nov 12 '18 at 15:54







  • 2





    @LostJon: This is part of the Promise syntax. While there are some advantages to the .catch() syntax, nothing is wrong with passing the onRejected handler into then.

    – Scott Sauyet
    Nov 12 '18 at 16:29












  • 2





    depends.... is it in a function that needs to return something?

    – epascarello
    Nov 12 '18 at 15:52











  • I need to get data from request function which is calling API

    – Anna K
    Nov 12 '18 at 15:52






  • 1





    Have you tried it? Does it change anything?

    – Nico Haase
    Nov 12 '18 at 15:52






  • 1





    What is the context for the second block of code you give? Is it inside a function which itself needs to return a promise? If you, then, yes, you would need return.

    – Jason Campbell
    Nov 12 '18 at 15:54







  • 2





    @LostJon: This is part of the Promise syntax. While there are some advantages to the .catch() syntax, nothing is wrong with passing the onRejected handler into then.

    – Scott Sauyet
    Nov 12 '18 at 16:29







2




2





depends.... is it in a function that needs to return something?

– epascarello
Nov 12 '18 at 15:52





depends.... is it in a function that needs to return something?

– epascarello
Nov 12 '18 at 15:52













I need to get data from request function which is calling API

– Anna K
Nov 12 '18 at 15:52





I need to get data from request function which is calling API

– Anna K
Nov 12 '18 at 15:52




1




1





Have you tried it? Does it change anything?

– Nico Haase
Nov 12 '18 at 15:52





Have you tried it? Does it change anything?

– Nico Haase
Nov 12 '18 at 15:52




1




1





What is the context for the second block of code you give? Is it inside a function which itself needs to return a promise? If you, then, yes, you would need return.

– Jason Campbell
Nov 12 '18 at 15:54






What is the context for the second block of code you give? Is it inside a function which itself needs to return a promise? If you, then, yes, you would need return.

– Jason Campbell
Nov 12 '18 at 15:54





2




2





@LostJon: This is part of the Promise syntax. While there are some advantages to the .catch() syntax, nothing is wrong with passing the onRejected handler into then.

– Scott Sauyet
Nov 12 '18 at 16:29





@LostJon: This is part of the Promise syntax. While there are some advantages to the .catch() syntax, nothing is wrong with passing the onRejected handler into then.

– Scott Sauyet
Nov 12 '18 at 16:29












1 Answer
1






active

oldest

votes


















1














This all depends upon what you want to do. If you wrote this version, which is slightly altered from your original but functionally the same:



function f1(city) 
return initialize(city).then(function(result)
const weather = result
const rain = result["data"][0]["precip"];
console.log(rain)
, function(err)
console.log(err)
)



then when you call



f1('Berlin')


you would request the Berlin result from the server, When the server responds, you would either pass to console.log the error received from the request or turn the returned body into a JS object, extract the appropriate precip property from it, and log that to the console. The resulting Promise value returned from f1 is useless, and the weather variable is unused and unusable.



If you want to log that precipitation, but still keep a useful return value, you can write:



function f2(city) 
return initialize(city).then(function(result)
const weather = result
const rain = result["data"][0]["precip"];
console.log(rain)
return weather // *** NOTE new line here ***
, function(err)
console.log(err)
)



This time calling with Berlin (and ignoring the error case from now on), you would log the precipitation returned, but also return a Promise for the whole Berlin weather node. That means you can still do this:



f2('Berlin')


to log Berlin's first precipitation value, but that now returns a useful value, so you could do



f2('Berlin').then(console.log)


to do that same logging, and then log the entire Berlin result.



Or you could do



f2('Berlin').then(function(weather) 
// do something useful with `weather` here.
, errorHandler)


But now note the cleanup that is available. First of all the rain variable in f2 is only used on the next line, and the weather one is simply a reference to the original result argument. So we can simplify it this way:



function f3(city) 
return initialize(city).then(function(result)
console.log(result["data"][0]["precip"])
return result
, function(err)
console.log(err)
)



This does the same thing more simply. But now there is a much more important simplification. It's quite possible that we don't need this function at all! If we have an error handler of some sort (even if it's just console.err), and we already have a function that does most of the weather handling we want, then instead of



f3('Berlin').then(function(weather) 
// do something useful with `weather` here.
, errorHandler)


we can add the logging line from f3 into this first callbak, and get the same result by calling directly to initialize:



initialize('Berlin').then(function(weather) 
console.log(weather["data"][0]["precip"])
// do something useful with `weather` here.
, errorHandler)


The reason this works is because initialize returns the result of calling then on the Promise, and then f2 and f3 also return either an altered value or the original one, keeping a Promise chain intact.



I would suggest that if you're in doubt you return something in any of these situations. It makes it much easier to continue working with values.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265651%2fpromise-function-do-i-need-use-return%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    This all depends upon what you want to do. If you wrote this version, which is slightly altered from your original but functionally the same:



    function f1(city) 
    return initialize(city).then(function(result)
    const weather = result
    const rain = result["data"][0]["precip"];
    console.log(rain)
    , function(err)
    console.log(err)
    )



    then when you call



    f1('Berlin')


    you would request the Berlin result from the server, When the server responds, you would either pass to console.log the error received from the request or turn the returned body into a JS object, extract the appropriate precip property from it, and log that to the console. The resulting Promise value returned from f1 is useless, and the weather variable is unused and unusable.



    If you want to log that precipitation, but still keep a useful return value, you can write:



    function f2(city) 
    return initialize(city).then(function(result)
    const weather = result
    const rain = result["data"][0]["precip"];
    console.log(rain)
    return weather // *** NOTE new line here ***
    , function(err)
    console.log(err)
    )



    This time calling with Berlin (and ignoring the error case from now on), you would log the precipitation returned, but also return a Promise for the whole Berlin weather node. That means you can still do this:



    f2('Berlin')


    to log Berlin's first precipitation value, but that now returns a useful value, so you could do



    f2('Berlin').then(console.log)


    to do that same logging, and then log the entire Berlin result.



    Or you could do



    f2('Berlin').then(function(weather) 
    // do something useful with `weather` here.
    , errorHandler)


    But now note the cleanup that is available. First of all the rain variable in f2 is only used on the next line, and the weather one is simply a reference to the original result argument. So we can simplify it this way:



    function f3(city) 
    return initialize(city).then(function(result)
    console.log(result["data"][0]["precip"])
    return result
    , function(err)
    console.log(err)
    )



    This does the same thing more simply. But now there is a much more important simplification. It's quite possible that we don't need this function at all! If we have an error handler of some sort (even if it's just console.err), and we already have a function that does most of the weather handling we want, then instead of



    f3('Berlin').then(function(weather) 
    // do something useful with `weather` here.
    , errorHandler)


    we can add the logging line from f3 into this first callbak, and get the same result by calling directly to initialize:



    initialize('Berlin').then(function(weather) 
    console.log(weather["data"][0]["precip"])
    // do something useful with `weather` here.
    , errorHandler)


    The reason this works is because initialize returns the result of calling then on the Promise, and then f2 and f3 also return either an altered value or the original one, keeping a Promise chain intact.



    I would suggest that if you're in doubt you return something in any of these situations. It makes it much easier to continue working with values.






    share|improve this answer



























      1














      This all depends upon what you want to do. If you wrote this version, which is slightly altered from your original but functionally the same:



      function f1(city) 
      return initialize(city).then(function(result)
      const weather = result
      const rain = result["data"][0]["precip"];
      console.log(rain)
      , function(err)
      console.log(err)
      )



      then when you call



      f1('Berlin')


      you would request the Berlin result from the server, When the server responds, you would either pass to console.log the error received from the request or turn the returned body into a JS object, extract the appropriate precip property from it, and log that to the console. The resulting Promise value returned from f1 is useless, and the weather variable is unused and unusable.



      If you want to log that precipitation, but still keep a useful return value, you can write:



      function f2(city) 
      return initialize(city).then(function(result)
      const weather = result
      const rain = result["data"][0]["precip"];
      console.log(rain)
      return weather // *** NOTE new line here ***
      , function(err)
      console.log(err)
      )



      This time calling with Berlin (and ignoring the error case from now on), you would log the precipitation returned, but also return a Promise for the whole Berlin weather node. That means you can still do this:



      f2('Berlin')


      to log Berlin's first precipitation value, but that now returns a useful value, so you could do



      f2('Berlin').then(console.log)


      to do that same logging, and then log the entire Berlin result.



      Or you could do



      f2('Berlin').then(function(weather) 
      // do something useful with `weather` here.
      , errorHandler)


      But now note the cleanup that is available. First of all the rain variable in f2 is only used on the next line, and the weather one is simply a reference to the original result argument. So we can simplify it this way:



      function f3(city) 
      return initialize(city).then(function(result)
      console.log(result["data"][0]["precip"])
      return result
      , function(err)
      console.log(err)
      )



      This does the same thing more simply. But now there is a much more important simplification. It's quite possible that we don't need this function at all! If we have an error handler of some sort (even if it's just console.err), and we already have a function that does most of the weather handling we want, then instead of



      f3('Berlin').then(function(weather) 
      // do something useful with `weather` here.
      , errorHandler)


      we can add the logging line from f3 into this first callbak, and get the same result by calling directly to initialize:



      initialize('Berlin').then(function(weather) 
      console.log(weather["data"][0]["precip"])
      // do something useful with `weather` here.
      , errorHandler)


      The reason this works is because initialize returns the result of calling then on the Promise, and then f2 and f3 also return either an altered value or the original one, keeping a Promise chain intact.



      I would suggest that if you're in doubt you return something in any of these situations. It makes it much easier to continue working with values.






      share|improve this answer

























        1












        1








        1







        This all depends upon what you want to do. If you wrote this version, which is slightly altered from your original but functionally the same:



        function f1(city) 
        return initialize(city).then(function(result)
        const weather = result
        const rain = result["data"][0]["precip"];
        console.log(rain)
        , function(err)
        console.log(err)
        )



        then when you call



        f1('Berlin')


        you would request the Berlin result from the server, When the server responds, you would either pass to console.log the error received from the request or turn the returned body into a JS object, extract the appropriate precip property from it, and log that to the console. The resulting Promise value returned from f1 is useless, and the weather variable is unused and unusable.



        If you want to log that precipitation, but still keep a useful return value, you can write:



        function f2(city) 
        return initialize(city).then(function(result)
        const weather = result
        const rain = result["data"][0]["precip"];
        console.log(rain)
        return weather // *** NOTE new line here ***
        , function(err)
        console.log(err)
        )



        This time calling with Berlin (and ignoring the error case from now on), you would log the precipitation returned, but also return a Promise for the whole Berlin weather node. That means you can still do this:



        f2('Berlin')


        to log Berlin's first precipitation value, but that now returns a useful value, so you could do



        f2('Berlin').then(console.log)


        to do that same logging, and then log the entire Berlin result.



        Or you could do



        f2('Berlin').then(function(weather) 
        // do something useful with `weather` here.
        , errorHandler)


        But now note the cleanup that is available. First of all the rain variable in f2 is only used on the next line, and the weather one is simply a reference to the original result argument. So we can simplify it this way:



        function f3(city) 
        return initialize(city).then(function(result)
        console.log(result["data"][0]["precip"])
        return result
        , function(err)
        console.log(err)
        )



        This does the same thing more simply. But now there is a much more important simplification. It's quite possible that we don't need this function at all! If we have an error handler of some sort (even if it's just console.err), and we already have a function that does most of the weather handling we want, then instead of



        f3('Berlin').then(function(weather) 
        // do something useful with `weather` here.
        , errorHandler)


        we can add the logging line from f3 into this first callbak, and get the same result by calling directly to initialize:



        initialize('Berlin').then(function(weather) 
        console.log(weather["data"][0]["precip"])
        // do something useful with `weather` here.
        , errorHandler)


        The reason this works is because initialize returns the result of calling then on the Promise, and then f2 and f3 also return either an altered value or the original one, keeping a Promise chain intact.



        I would suggest that if you're in doubt you return something in any of these situations. It makes it much easier to continue working with values.






        share|improve this answer













        This all depends upon what you want to do. If you wrote this version, which is slightly altered from your original but functionally the same:



        function f1(city) 
        return initialize(city).then(function(result)
        const weather = result
        const rain = result["data"][0]["precip"];
        console.log(rain)
        , function(err)
        console.log(err)
        )



        then when you call



        f1('Berlin')


        you would request the Berlin result from the server, When the server responds, you would either pass to console.log the error received from the request or turn the returned body into a JS object, extract the appropriate precip property from it, and log that to the console. The resulting Promise value returned from f1 is useless, and the weather variable is unused and unusable.



        If you want to log that precipitation, but still keep a useful return value, you can write:



        function f2(city) 
        return initialize(city).then(function(result)
        const weather = result
        const rain = result["data"][0]["precip"];
        console.log(rain)
        return weather // *** NOTE new line here ***
        , function(err)
        console.log(err)
        )



        This time calling with Berlin (and ignoring the error case from now on), you would log the precipitation returned, but also return a Promise for the whole Berlin weather node. That means you can still do this:



        f2('Berlin')


        to log Berlin's first precipitation value, but that now returns a useful value, so you could do



        f2('Berlin').then(console.log)


        to do that same logging, and then log the entire Berlin result.



        Or you could do



        f2('Berlin').then(function(weather) 
        // do something useful with `weather` here.
        , errorHandler)


        But now note the cleanup that is available. First of all the rain variable in f2 is only used on the next line, and the weather one is simply a reference to the original result argument. So we can simplify it this way:



        function f3(city) 
        return initialize(city).then(function(result)
        console.log(result["data"][0]["precip"])
        return result
        , function(err)
        console.log(err)
        )



        This does the same thing more simply. But now there is a much more important simplification. It's quite possible that we don't need this function at all! If we have an error handler of some sort (even if it's just console.err), and we already have a function that does most of the weather handling we want, then instead of



        f3('Berlin').then(function(weather) 
        // do something useful with `weather` here.
        , errorHandler)


        we can add the logging line from f3 into this first callbak, and get the same result by calling directly to initialize:



        initialize('Berlin').then(function(weather) 
        console.log(weather["data"][0]["precip"])
        // do something useful with `weather` here.
        , errorHandler)


        The reason this works is because initialize returns the result of calling then on the Promise, and then f2 and f3 also return either an altered value or the original one, keeping a Promise chain intact.



        I would suggest that if you're in doubt you return something in any of these situations. It makes it much easier to continue working with values.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 '18 at 17:20









        Scott SauyetScott Sauyet

        20.8k22757




        20.8k22757





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53265651%2fpromise-function-do-i-need-use-return%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

            Crossroads (UK TV series)

            ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế