ES6承诺 - 将承诺链接起来并将争论传递到链条上的正确方法

时间:2017-12-11 21:34:43

标签: javascript ajax ecmascript-6

我是ES6承诺的新手,并且有两个我想要链接的承诺。我遇到的问题是,我希望将第一个承诺的结果传递给第二个.then()语句。这是我到目前为止:

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();
    });
}

我似乎无法弄清楚如何正确地链接这些,以便在链的末尾我可以访问两个承诺结果。有人可以指出我正确的方向并告诉我哪里出错了?我尝试将resOne作为参数传递给2nd then语句,但仍然无法正常工作

2 个答案:

答案 0 :(得分:0)

如果您需要访问先前的结果,您应该链接内部承诺。这会增加额外的缩进程度(遗憾的是)但如果你不能使用async / await,它可能是最干净的方法。

所以对于你的代码片段:

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();
        })
    });
}

答案 1 :(得分:0)

根据您是否使用ES6代码,您可以使用async / await

相对简单地完成此操作

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

这两项承诺都将得到处理。两者都解决后,您分别在result1result2中获取其值。然后,您可以将它们视为常规值。这可以防止你将参数传递给回调圣诞树;)

相关问题