提取Yelp的评级

时间:2017-08-15 00:10:50

标签: javascript ajax api yelp

我有这个locations.json文件,我存储标题,位置(纬度,长度)和电话号码。我现在面临的问题对其他人来说似乎微不足道,但作为初学者,我无法按照自己喜欢的方式工作。我想仅从Yelp的api v3中提取评级,并将其添加到locations.rating数组中。我下面的代码附加了从Yelp返回的整个响应对象,但是当我尝试console.log(response.businesses [0] .rating)时,它只能打印出评级。如何让它仅返回评级?提前谢谢。

var yelpPhoneSearch = "https://api.yelp.com/v3/businesses/search/phone?phone=";
var cors_anywhere_url = 'https://cors-anywhere.herokuapp.com/';  // Yelp v3 api doesn't support CORS, need to use this 3rd party proxy service
var locations = [];
$.getJSON('/locations.json', function(data){
  for (var i = 0; i < data.length; i++) {
    var schools = {};
    schools.title = data[i].title;
    schools.location = data[i].location;
    schools.phone = data[i].phone;
    schools.rating = $.ajax({
      "async": true,
      "crossDomain": true,
      "url": cors_anywhere_url + yelpPhoneSearch + data[i].phone,
      "method": "GET",
      "headers": {
        "authorization": "Bearer " + yelpToken.access_token,
        "cache-control": "public, max-age=31536000",
      }
    }).done(function(response){
      // console.log(response);
      var rating = response.businesses[0].rating;
      return rating;
    });
    // Push all infos to locations array
    locations.push(schools);
  }
});

1 个答案:

答案 0 :(得分:0)

使用jQuery promises(几乎像普通的Promises,除了保证在旧浏览器中可用),你可以像这样重写你的代码

var yelpPhoneSearch = "https://api.yelp.com/v3/businesses/search/phone?phone=";
var cors_anywhere_url = 'https://cors-anywhere.herokuapp.com/';  // Yelp v3 api doesn't support CORS, need to use this 3rd party proxy service

$.getJSON('/locations.json')
.then(function(data){
    return $.when.apply($, data.map(function(school) {
        return $.ajax({
            "async": true,
            "crossDomain": true,
            "url": cors_anywhere_url + yelpPhoneSearch + school.phone,
            "method": "GET",
            "headers": {
                "authorization": "Bearer " + yelpToken.access_token,
                "cache-control": "public, max-age=31536000",
            }
        }).then(function(response) {
            return {
                title: school.title,
                location: school.location,
                phone: school.phone,
                rating: response.businesses[0].rating
            };
        });
    }));
}).then(function() {
    var locations = [].slice.call(arguments);
    /* here locations is an array of 
    {
        title,
        location,
        phone,
        rating
    }
    */
});

注意:由于$.ajax的异步性质,您无法访问最后.then之外的结果数组,因为异步代码是异步的

为了完整性 - 带有原生Promise的ES2015 +,代码将是

$.getJSON('/locations.json').then(data => 
    Promise.all(data.map(school => 
        $.ajax({
            "async": true,
            "crossDomain": true,
            "url": cors_anywhere_url + yelpPhoneSearch + school.phone,
            "method": "GET",
            "headers": {
                "authorization": "Bearer " + yelpToken.access_token,
                "cache-control": "public, max-age=31536000",
            }
        }).then(response => ({
            title: school.title,
            location: school.location,
            phone: school.phone,
            rating: response.businesses[0].rating
        }))
    ))
).then(locations => {
    /* here locations is an array of 
    {
        title,
        location,
        phone,
        rating
    }
    */
});

如果您需要在代码的其他部分访问locations,并假设您的问题中的代码不是从函数中获取的(即,vars都是全局范围的)

var yelpPhoneSearch = "https://api.yelp.com/v3/businesses/search/phone?phone=";
var cors_anywhere_url = 'https://cors-anywhere.herokuapp.com/';  // Yelp v3 api doesn't support CORS, need to use this 3rd party proxy service

var locations = $.getJSON('/locations.json')
.then(function(data){
    return $.when.apply($, data.map(function(school) {
        return $.ajax({
            "async": true,
            "crossDomain": true,
            "url": cors_anywhere_url + yelpPhoneSearch + school.phone,
            "method": "GET",
            "headers": {
                "authorization": "Bearer " + yelpToken.access_token,
                "cache-control": "public, max-age=31536000",
            }
        }).then(function(response) {
            return {
                title: school.title,
                location: school.location,
                phone: school.phone,
                rating: response.businesses[0].rating
            };
        });
    }));
}).then(function() {
    return [].slice.call(arguments);
});

现在,在您需要使用位置的代码中,您需要使用典型的Promise方法来访问结果

locations.then(function(value) {
    // in here,  value is an array of locations
});

在实际代码中看不到如何使用locations,这可能不像上面那么容易,因为一旦处理异步代码,就需要正确处理它