如何在节点js中使节点js的异步功能处于同步状态

时间:2016-02-02 05:27:22

标签: javascript node.js asynchronous synchronous aws-lib

在节点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);
            }
        });
    }

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

2 个答案:

答案 0 :(得分:2)

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

- (void)application:(UIApplication *)app didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //No Need to store the push notification if it is in active or in closed state we can directly navigate to the screens

    NSLog(@"notification didReceive method called");

    if([app applicationState] == UIApplicationStateInactive) {
        //If the application state was inactive, this means the user pressed     an action button
        //Handle the code after push notification received  
    }
    else if ([app applicationState] == UIApplicationStateActive) {
        //Application is in Active state handle the push notification here
    }
}

答案 1 :(得分:1)

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

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