在函数中设置全局变量

时间:2014-05-23 18:58:42

标签: javascript initialization global-variables scope

我想要做的是初始化函数外部的全局变量,在函数内设置变量,然后在函数后打印变量值。但是,当我打印时,它会注销No Message Provided

在这种情况下,我尝试使用itemLocation变量执行此操作。

var itemLocation;
Parse.Cloud.define("eBayCategorySearch", function (request, response) {
    url = 'http://svcs.ebay.com/services/search/FindingService/v1';
    Parse.Cloud.httpRequest({
        url: url,
        params: {
            'OPERATION-NAME': 'findItemsByKeywords',
                'SERVICE-VERSION': '1.12.0',
                'SECURITY-APPNAME': '*APP ID GOES HERE*',
                'GLOBAL-ID': 'EBAY-US',
                'RESPONSE-DATA-FORMAT': 'JSON',
                'itemFilter(0).name=ListingType': 'itemFilter(0).value=FixedPrice',
                'keywords': request.params.item,
        },
        success: function (httpResponse) {
            // parses results
            var httpresponse = JSON.parse(httpResponse.text);
            var items = [];
            httpresponse.findItemsByKeywordsResponse.forEach(function (itemByKeywordsResponse) {
                itemByKeywordsResponse.searchResult.forEach(function (result) {
                    result.item.forEach(function (item) {
                        items.push(item);
                    });
                });
            });


            // count number of times each unique primaryCategory shows up (based on categoryId), returns top two IDs and their respective names
            var categoryIdResults = {};

            // Collect two most frequent categoryIds
            items.forEach(function (item) {
                var id = item.primaryCategory[0].categoryId;
                if (categoryIdResults[id]) categoryIdResults[id]++;
                else categoryIdResults[id] = 1;
            });

            var top2 = Object.keys(categoryIdResults).sort(function (a, b) {
                return categoryIdResults[b] - categoryIdResults[a];
            }).slice(0, 2);
            console.log('Top category Ids: ' + top2.join(', '));

            var categoryNameResults = {};

            // Collect two most frequent categoryNames  
            items.forEach(function (item) {
                var categoryName = item.primaryCategory[0].categoryName;
                if (categoryNameResults[categoryName]) categoryNameResults[categoryName]++;
                else categoryNameResults[categoryName] = 1;
            });

            var top2Names = Object.keys(categoryNameResults).sort(function (a, b) {
                return categoryNameResults[b] - categoryNameResults[a];
            }).slice(0, 2);
            console.log('Top category Names: ' + top2Names.join(', '));

            // compare categoryIdResults to userCategory object
            //Extend the Parse.Object class to make the userCategory class
            var userCategory = Parse.Object.extend("userCategory");

            //Use Parse.Query to generate a new query, specifically querying the userCategory object.
            query = new Parse.Query(userCategory);

            //Set constraints on the query.
            query.containedIn('categoryId', top2);
            query.equalTo('parent', Parse.User.current())

            //Submit the query and pass in callback functions.
            var isMatching = false;
            query.find({
                success: function (results) {
                    var userCategoriesMatchingTop2 = results;
                    console.log("userCategory comparison success!");
                    console.log(results);

                    for (var i = 0; i < results.length; i++) {
                        itemCondition = results[i].get("itemCondition");
                        console.log(itemCondition);

                        itemLocation = results[i].get("itemLocation");
                        console.log(itemLocation);

                        minPrice = results[i].get("minPrice");
                        console.log(minPrice);

                        maxPrice = results[i].get("maxPrice");
                        console.log(maxPrice);

                        itemSearch = request.params.item;
                        console.log(itemSearch);
                    }

                    if (userCategoriesMatchingTop2 && userCategoriesMatchingTop2.length > 0) {
                        isMatching = true;
                    }

                    response.success({
                        "results": [{
                            "Number of top categories": top2.length
                        }, {
                            "Top category Ids": top2
                        }, {
                            "Top category names": top2Names
                        }, {
                            "Number of matches": userCategoriesMatchingTop2.length
                        }, {
                            "User categories that match search": userCategoriesMatchingTop2
                        }, {
                            "Matching Category Condition": itemCondition
                        }, {
                            "Matching Category Location": itemLocation
                        }, {
                            "Matching Category MaxPrice": maxPrice
                        }, {
                            "Matching Category MinPrice": minPrice
                        }, {
                            "Search Term": itemSearch
                        },

                        ]
                    });
                    console.log('User categories that match search: ', results);
                },
                error: function (error) {
                    //Error Callback
                    console.log("An error has occurred");
                    console.log(error);
                }
            });
        },
        error: function (httpResponse) {
            console.log('error!!!');
            response.error('Request failed with response code ' + httpResponse.status);
        }
    });
});
console.log(itemLocation);

1 个答案:

答案 0 :(得分:0)

我不确定你想要实现的目标,但这是单程来做你想做的事。

var itemLocation;
var promise; // variable holding the promise
Parse.Cloud.define("eBayCategorySearch", function (request, response) {
    url = 'http://svcs.ebay.com/services/search/FindingService/v1';
    // set the promise
    promise = Parse.Cloud.httpRequest({
        // your code goes here (setting the variables)
    });
});

// once the promise has been resolved
promise.then(function(resp){
    console.log(itemLocation);
});
相关问题