如何使节点js的asynchronousfunction在节点js中同步处理

在节点js我有一个aws API调用for循环。

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

预期的结果是,第一个结果返回值后,第二个呼叫请求应该去。 但是这里请求/响应是asynchronous运行的。如何使下一个结果等到上一个调用返回响应。 即使速度很慢也可以。

你可以使用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'); } ); 

如果您更喜欢使用promise而不是callback函数,则可以简单地使用recursion来实现同步,而不需要任何外部库来定义代码执行的stream程。

你可以用callback来做到这一点,但代码看起来很可怕。