如何通过映射的承诺传递数据?

How to pass data through mapped promises?

我有一个三阶段混搭脚本,用于检查本地音像店的最新租赁,然后从烂番茄 (RT) 获取他们的评论百分比和共识:

$(document).ready(function(){
    $('button').click(function (){
        getNewRentals(url).then(function(ids){
            var mapped = ids.map(function(id, f){
                return function(){
                    return getRentalSpecs(id, f).then(function (f, name, year){
                        return getRotten(f, name, year); // Gets only f!
                    });
                }
            });
            var m = mapped[0]();
            for(var i = 1; i < mapped.length; i++) {
                m = m.then(mapped[i]);
            }
        });
    });
});

一切正常,只是只有f传给了最后一个函数getRotten,但是没有 film 姓名或 年份 。映射循环一定有问题,因为所有三个函数都使用相同的 jquery getJSON(通过 Yahoo YQL),它们完全相同地包装在标准 js 承诺中,这些承诺完全解析为代码中提到的参数。因此,如果数据从第一个函数传递到第二个函数,为什么不从第二个函数传递到第三个函数呢?

我已经在这个 callback/promise 地狱里煎熬了几个星期了,现在已经全身起泡了。这也是我第一次post到所以,所以请多多包涵。

一个 promise 表示一个值,它作为一个参数传递给任何 then 处理程序。在需要传递多个值的地方使用对象或数组(以更合适的为准):

$(document).ready(function () {
    $('button').click(loadRotten);
});

function loadRotten () {
    return getNewRentals(url)
        .then(function (ids) {
            return Promise.all(ids.map(getRentalSpecs));
        })
        .then(function (objects) {
            return Promise.all(objects.map(function (obj) {
                return GetRotten(obj.f, obj.name, obj.year);
            });
            // Or refactor `GetRotten` to accept a single object
            // return Promise.all(objects.map(GetRotten));
        });
    });
}

// Or, using ES6, assuming refactor of `GetRotten`:

function loadRotten () {
    return getNewRentals(url)
        .then(ids => Promise.all(ids.map(getRentalSpecs)))
        .then(objects => Promise.all(objects.map(GetRotten));
}    

您将必须修改 getRentalSpecs 以便它解析为具有属性 fnameyear.

的对象

我已重构您的代码以使用 Promise.all(),这样更容易理解。似乎没有必要映射到函数表达式并手动依次调用它们,因为它们彼此不依赖。