如何使处理节点js的异步功能在节点js中同步

How to make handle asynchronous functionality of node js to synchronous in node js

在节点 js 中,我在 for 循环中有一个 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);
            }
        });
    }

预期结果是,在第一个结果 returns 值之后,第二个调用请求应该进行。但是这里 request/response 是 运行 asynchronously.How 使下一个结果等到上一个调用 returns 响应。慢点也没关系

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

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

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