2

在节点 js 中,我在 for loop 中有一个 aws API 调用。

var prodAdvOptions = {
        host : "webservices.amazon.in",
        region : "IN",
        version : "2013-08-01",
        path : "/onca/xml"
    };
    prodAdv = aws.createProdAdvClient(awsAccessKeyId, awsSecretKey, awsAssociateTag, prodAdvOptions);
    var n=100//Just for test
    for (var i = 0; i <=n; i++) {
        prodAdv.call("ItemSearch", {
            SearchIndex : "All",
            Keywords : "health,fitness,baby care,beauty",
            ResponseGroup : 'Images,ItemAttributes,Offers,Reviews',
            Availability : 'Available',
            ItemPage : 1

        }, function(err, result) {

            if (err) {
                console.log(err);
            } else {
                console.log(result);
            }
        });
    }

预期的结果是,在第一个结果返回值后,第二个调用请求应该去。但是这里的请求/响应是异步运行的。如何让下一个结果等到上一个调用返回响应。即使速度很慢也没关系。

4

2 回答 2

2

您可以使用 async.whilst() 作为您的for循环。像这样的东西:

var async = require('async');

var prodAdvOptions = {
    host : "webservices.amazon.in",
    region : "IN",
    version : "2013-08-01",
    path : "/onca/xml"
};
var prodAdv = aws.createProdAdvClient(awsAccessKeyId, awsSecretKey, awsAssociateTag, prodAdvOptions);

var n=100;//Just for test
var i = 0;  // part 1 of for loop (var i = 0)
async.whilst(
    function () { return i <= n; },  // part 2 of for loop (i <=n)
    function (callback) {
        prodAdv.call("ItemSearch", {
            SearchIndex : "All",
            Keywords : "health,fitness,baby care,beauty",
            ResponseGroup : 'Images,ItemAttributes,Offers,Reviews',
            Availability : 'Available',
            ItemPage : 1
        }, function(err, result) {
            if (err) {
                console.log(err);
            } else {
                console.log(result);
            }
            i++;          // part 3 of for loop (i++)
            callback();
        });
    },
    function (err) {
        console.log('done with all items from 0 - 100');
    }
);
于 2016-02-02T06:04:58.347 回答
1

如果您更喜欢使用承诺而不是回调,您可以简单地使用递归来实现同步,而无需任何外部库来定义代码执行流程。

你可以通过回调来做到这一点,但代码看起来很糟糕。

于 2016-02-02T06:59:36.173 回答