Making two sequential asynchronous requests using promisesReading the contents at three URLs using...

Is there a name of the flying bionic bird?

What is it called when one voice type sings a 'solo'?

Where to refill my bottle in India?

Copycat chess is back

aging parents with no investments

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

Does the average primeness of natural numbers tend to zero?

Information to fellow intern about hiring?

How do I create uniquely male characters?

Re-submission of rejected manuscript without informing co-authors

Can the Produce Flame cantrip be used to grapple, or as an unarmed strike, in the right circumstances?

How to move the player while also allowing forces to affect it

What is the command to reset a PC without deleting any files

Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?

Why do we use polarized capacitors?

Is there a way to make member function NOT callable from constructor?

Can I find out the caloric content of bread by dehydrating it?

A poker game description that does not feel gimmicky

Symmetry in quantum mechanics

Calculate Levenshtein distance between two strings in Python

COUNT(*) or MAX(id) - which is faster?

How to make payment on the internet without leaving a money trail?

How can I add custom success page

What are the advantages and disadvantages of running one shots compared to campaigns?



Making two sequential asynchronous requests using promises


Reading the contents at three URLs using PromisesMake sequential fadeIn() promises more manageableRewriting authentication controller using promisesAsynchronous database lookups in Node.JS using PromisesHandling login using promisesDeleting rooms using nested promisesFetching and shortening URLs with API calls using PromisesAngularJS application for working with the Facebook API (using the cordova-plugin-facebook4 plugin)Webscraping with CheerioExecute promise tree in order of declaration






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







0












$begingroup$


The following code is making two asynchronous requests to obtain the desired data. The second request needs to access the data from the first request, hence I need to nest it. I know that it is better to chain promises, but this is a case where nesting seems necessary.



However the lint raises a warning: avoid nesting promises. Should I ignore the warning or there is a better way to rewrite the code?



function get_note_full(note_id) {
return db.collection('notes').doc(note_id).get()
.then(doc => {
const data = doc.data();
return get_author_data(data.author_uid)
.then(author => {
return ({
id: note_id,
title: data.title,
text: data.text,
author: author
});
});
});
}









share|improve this question











$endgroup$



















    0












    $begingroup$


    The following code is making two asynchronous requests to obtain the desired data. The second request needs to access the data from the first request, hence I need to nest it. I know that it is better to chain promises, but this is a case where nesting seems necessary.



    However the lint raises a warning: avoid nesting promises. Should I ignore the warning or there is a better way to rewrite the code?



    function get_note_full(note_id) {
    return db.collection('notes').doc(note_id).get()
    .then(doc => {
    const data = doc.data();
    return get_author_data(data.author_uid)
    .then(author => {
    return ({
    id: note_id,
    title: data.title,
    text: data.text,
    author: author
    });
    });
    });
    }









    share|improve this question











    $endgroup$















      0












      0








      0





      $begingroup$


      The following code is making two asynchronous requests to obtain the desired data. The second request needs to access the data from the first request, hence I need to nest it. I know that it is better to chain promises, but this is a case where nesting seems necessary.



      However the lint raises a warning: avoid nesting promises. Should I ignore the warning or there is a better way to rewrite the code?



      function get_note_full(note_id) {
      return db.collection('notes').doc(note_id).get()
      .then(doc => {
      const data = doc.data();
      return get_author_data(data.author_uid)
      .then(author => {
      return ({
      id: note_id,
      title: data.title,
      text: data.text,
      author: author
      });
      });
      });
      }









      share|improve this question











      $endgroup$




      The following code is making two asynchronous requests to obtain the desired data. The second request needs to access the data from the first request, hence I need to nest it. I know that it is better to chain promises, but this is a case where nesting seems necessary.



      However the lint raises a warning: avoid nesting promises. Should I ignore the warning or there is a better way to rewrite the code?



      function get_note_full(note_id) {
      return db.collection('notes').doc(note_id).get()
      .then(doc => {
      const data = doc.data();
      return get_author_data(data.author_uid)
      .then(author => {
      return ({
      id: note_id,
      title: data.title,
      text: data.text,
      author: author
      });
      });
      });
      }






      javascript node.js promise






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      200_success

      131k17157422




      131k17157422










      asked yesterday









      Emanuele PaoliniEmanuele Paolini

      2,0171713




      2,0171713






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          You should be able to convert that code to using async / await from ES2017. Notice that I changed the function names to suit general JavaScript naming standards (camelCase for functions and variables, etc.)



          async function getFullNote(noteId) {
          const note = await db.collection('notes').doc(note_id).get();
          const author = await getAuthorData(note.author_uid);
          return {
          id: note_id,
          title: data.title,
          ext: data.text,
          author: author
          }
          }


          This is how MDN defines an async function:



          An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.


          Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function






          share|improve this answer











          $endgroup$














            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            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: "196"
            };
            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: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            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%2fcodereview.stackexchange.com%2fquestions%2f217001%2fmaking-two-sequential-asynchronous-requests-using-promises%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









            0












            $begingroup$

            You should be able to convert that code to using async / await from ES2017. Notice that I changed the function names to suit general JavaScript naming standards (camelCase for functions and variables, etc.)



            async function getFullNote(noteId) {
            const note = await db.collection('notes').doc(note_id).get();
            const author = await getAuthorData(note.author_uid);
            return {
            id: note_id,
            title: data.title,
            ext: data.text,
            author: author
            }
            }


            This is how MDN defines an async function:



            An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.


            Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function






            share|improve this answer











            $endgroup$


















              0












              $begingroup$

              You should be able to convert that code to using async / await from ES2017. Notice that I changed the function names to suit general JavaScript naming standards (camelCase for functions and variables, etc.)



              async function getFullNote(noteId) {
              const note = await db.collection('notes').doc(note_id).get();
              const author = await getAuthorData(note.author_uid);
              return {
              id: note_id,
              title: data.title,
              ext: data.text,
              author: author
              }
              }


              This is how MDN defines an async function:



              An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.


              Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function






              share|improve this answer











              $endgroup$
















                0












                0








                0





                $begingroup$

                You should be able to convert that code to using async / await from ES2017. Notice that I changed the function names to suit general JavaScript naming standards (camelCase for functions and variables, etc.)



                async function getFullNote(noteId) {
                const note = await db.collection('notes').doc(note_id).get();
                const author = await getAuthorData(note.author_uid);
                return {
                id: note_id,
                title: data.title,
                ext: data.text,
                author: author
                }
                }


                This is how MDN defines an async function:



                An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.


                Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function






                share|improve this answer











                $endgroup$



                You should be able to convert that code to using async / await from ES2017. Notice that I changed the function names to suit general JavaScript naming standards (camelCase for functions and variables, etc.)



                async function getFullNote(noteId) {
                const note = await db.collection('notes').doc(note_id).get();
                const author = await getAuthorData(note.author_uid);
                return {
                id: note_id,
                title: data.title,
                ext: data.text,
                author: author
                }
                }


                This is how MDN defines an async function:



                An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.


                Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited yesterday

























                answered yesterday









                TomGTomG

                48629




                48629






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


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


                    Use MathJax to format equations. MathJax reference.


                    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%2fcodereview.stackexchange.com%2fquestions%2f217001%2fmaking-two-sequential-asynchronous-requests-using-promises%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

                    is 'sed' thread safeWhat should someone know about using Python scripts in the shell?Nexenta bash script uses...

                    How do i solve the “ No module named 'mlxtend' ” issue on Jupyter?

                    Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...