当使用q时,我得到相同的响应,它循环的次数:

function start() {
    var the_promises = [];
    var api_info = config.AFV
    var deferred = Q.defer();
    var extPath = '/search/'
    var callType = 'GET'
    var mymd = buildmd5(api_info, extPath, callType);

    for(var page=1;page<4;page++) {

        console.log('getting page:'+page)
        new Client().get(url'+page, function(data, response){
            deferred.resolve(data);
        });
        the_promises.push(deferred.promise);
    }
    return Q.all(the_promises);
}

start().then(function (clips) {
    inspect(clips)
});


输出:
    resultPageNumber:['1'],
    resultPageNumber:['1'],
    resultPageNumber:['1'],
    resultPageNumber:['1'],

我觉得我可能有var deferred = Q.defer();在错误的地方,它就不能兑现不同的承诺。我知道此版本的代码不起作用,但我只关心诺言。谢谢!

最佳答案

您需要为每个新客户端创建一个新的延迟。并在立即调用的函数中抛出该循环体以适当地确定var的范围。

function start() {
    var the_promises = [];
    var api_info = config.AFV;
    var extPath = '/search/';
    var callType = 'GET';
    var mymd = buildmd5(api_info, extPath, callType);

    for(var page=1;page<4;page++) {
        (function() {
            var deferred = Q.defer();
            console.log('getting page:'+page);
            new Client().get('url'+page, function(data, response){
                deferred.resolve(data);
            });
           the_promises.push(deferred.promise);
        }());
    }
    return Q.all(the_promises);
}

start().then(function (clips) {
    inspect(clips);
});

09-17 18:18