user3142695 user3142695 - 1 month ago 7
Javascript Question

JS: Nested promises

I do not understand how to chain promises:

getUser
is a promise function and also
search
is a promise function.
getUser
will return a language value.

With this data is not an array value, which should be returned by the
search
function

getUser(userId)
.then(({ language }) => {
const data = search('content', language)
res.send(200, {
content: data,
user: { language }
})
})
.catch((error) => next(error))

Answer Source

To avoid nesting, you can use Promise.all: this will allow you to pass the language value through the chain as well:

getUser(userId)
    .then(({ language }) => 
        Promise.all([language, search('content', language)])
    ).then(([language, data]) => 
        res.send(200, {
            content: data,
            user: { language }
        })
    ).catch((error) => next(error))