javascript - 如何避免所附片段中 JavaScript 中的代码重复?

标签 javascript callback overloading

我正在尝试使用 Open Weather map 查找天气,我有 2 个方法,findWeatherByLocationfindWeatherByCity。我假设 JavaScript 不支持方法重载,因此有两个不同的名称。这两种方法都接受将被触发的回调函数并执行相同的操作。

function findWeatherForCity(senderID, city, countryCode, callback) {
    //Lets configure and request
    request({
        url: constants.OPEN_WEATHER_MAP_BASE_URL, //URL to hit
        qs: {
            q: city + ',' + countryCode,
            appid: constants.OPEN_WEATHER_MAP_API_KEY
        }, //Query string data
        method: 'GET', //Specify the method
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            let weather = getWeatherReport(JSON.parse(body));
            callback(weather ? weather : null);
        }
        else {
            console.error(response.error);
            callback(null);
        }
    });
}

/*
 lat, lon coordinates of the location of your interest   
 * http://openweathermap.org/current
 */

function findWeatherForLocation(senderID, location, callback) {
    //Lets configure and request
    request({
        url: constants.OPEN_WEATHER_MAP_BASE_URL, //URL to hit
        qs: {
            lat: location.lat,
            lon: location.lon,
            appid: constants.OPEN_WEATHER_MAP_API_KEY
        }, //Query string data
        method: 'GET', //Specify the method
    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            let report = getWeatherReport(JSON.parse(body));
            callback(report ? report : null);
        }
        else {
            console.error(response.error)
            callback(null);
        }
    });
}

如您所见,function(error, response, body) 在两个地方执行相同的操作。如果我创建一个单独的 function(error, response, body) (对于 findWeatherByCityfindWeatherByLocation 都很常见,我如何触发 >回调

感谢您提前提供的帮助。

最佳答案

我已经使用 Promise 来重构回调并整理代码,但你可以用回调替换它们,尽管我不推荐这样做(已经是 2016 年了)。

/* you are not using senderID anywhere but i left it cuz you had it.*/
function findWeather(senderID, queryType, options) {
  return new Promise(function(resolve, reject) {
    var queryObj = {
      appid: constants.OPEN_WEATHER_MAP_API_KEY
    };
    if (queryType === 'city') {
      queryObj.q = options.city + ',' + options.countryCode;
    } else if (queryType === 'location') {
      queryObj.lat= options.lat;
      queryObj.lon= options.lon;
      }
    } else {
      reject('no valid queryType');
    }

    request({
      url: constants.OPEN_WEATHER_MAP_BASE_URL,
      qs: queryObj,
      method: 'GET'
    }, function(err, response, body) {
      if (!error && response.statusCode == 200) {
        let report = getWeatherReport(JSON.parse(body));
        resolve(report ? report : null);
      } else {
        reject(response.error);
      }
    });
  });
}

/*USAGE*/
findWeather(1, 'city', {
    city: 'Ramallah',
    countryCode: '00970'
  })
  .then(function(data) {
    console.log(data);
  });

findWeather(1, 'location', {
    lat: 1,
    lon: 2
  })
  .then(function(data) {
    console.log(data);
  })
  .catch(function(err) {
    console.log(err);
  });

关于javascript - 如何避免所附片段中 JavaScript 中的代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38930488/

相关文章:

javascript - Mocha : how to test this async method that returns a callback?

c++ - `void f(A<0>, tuple<T *...>)` 不是比 `void f(A<I>, tuple<T *...>)` 更专业吗?

c++ - 将类型信息传递给函数代替虚拟模板函数 C++

javascript - 当元素已经处于事件状态时关闭 jquery 弹出窗口

javascript - 即使正确渲染,EJS 变量也会引发错误

javascript - IE9 错误 80020102,使用带有 doctype strict 的 vbscript Preserve 关键字

http - XMLHttpRequest 如何知道何时调用它的回调?

javascript - 如何在 Firebug 中监控事件?

javascript - 如何发送带有 header 参数的 HTTP 请求?

f# - F# 度量的重载