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
            });
        });
    });
}
\$\endgroup\$

1 Answer 1

1
\$\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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.