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
 });
 });
 });
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 7, 2019 at 6:57
\$\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

answered Apr 7, 2019 at 11:11
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.