-2

I'm new to ES6 promises and have two promises that I would like to chain. The issue i'm having is that I would like to pass down the result from the first promise down to the 2nd .then() statement. here is what I have so far:

export function resolvePage(pageName, contentType) {
    return contentful.fetchContentByQuery(contentType, {
        'fields.slug': pageName,
    })
    .then((resOne) => {
        return contentful.client.getEntries({
            'content_type': 'blogArticle'
        })
    })
    .then((resTwo) => {
        console.log(resOne)
        console.log(resTwo)

        return Promise.reject();
    });
}

I can't seem to figure out how to chain these properly so that at the end of the chain I have access to both promise results. Could someone please point me in the right direction and tell me where i'm going wrong? I tried passing resOne as a parameter to the 2nd then statement but still wouldn't work

red house 87
  • 1,837
  • 9
  • 50
  • 99

2 Answers2

0

If you need access to a prior result, you should chain off of the inner promise. This adds an extra level of indentation (sadly) but it's probably the cleanest way to do this if you cant use async/await.

So for your snippet:

export function resolvePage(pageName, contentType) {
    return contentful.fetchContentByQuery(contentType, {
        'fields.slug': pageName,
    })
    .then((resOne) => {
        return contentful.client.getEntries({
            'content_type': 'blogArticle'
        }).then((resTwo) => {
            // Note that this is now chaining on the inner promise
            // So it has access to resOne via the closure.
            console.log(resOne)
            console.log(resTwo)

            return Promise.reject();
        })
    });
}
CRice
  • 29,968
  • 4
  • 57
  • 70
0

Depending on whether you are using ES6 code, you can do this relatively easy with async/await

const {result1, result2} = await Promise.all([promise1, promise2]);

Both promises will be handled. Once both have resolved, you obtain their values in result1 and result2 respectively. You can then treat them as regular values. This prevent you from passing down argument into the callback christmas tree ;)

Rogier Slag
  • 526
  • 3
  • 7