Nodejs: How To Avoid Nested .then() When Using Async/await
Solution 1:
I would say you still need one then
requester.makeRequest(geocode_url +`?locate=${req.query.q}&json=1`
    + geocode_token)
  .then(asyncfunction(city){
    var final_result = []
    var lat = city.latt;
    var long = city.longt;
    // request to get list of cities closer to that location,//takes latitude and longitude as parameters
    closer_cities = await requester.makeRequest(metaweather_url + '?lattlong='+ lat + ',' + long);
    var cities_len = closer_cities.length;
    for(i = 0; i < closer_cities.length; i++) {
      woeid = closer_cities[i].woeid//request to get weather using woeid parameter
      weather = await requester.makeRequest(woeid_url + woeid)
      var lattlong = weather.latt_long;
      onwater = await awaitrequester.makeRequest(onwater_url+ lattlong + '?access_token=' + water_access_token)
      var temp = Object.assign(weather, onwater)
      final_result.push(temp)
      if (final_result.length == cities_len) {
        res.status(200).json({error: false, data: {message: final_result}})
      }
    }
  })
Edit: I don't really think my answer is relevant for your problem sorry
Solution 2:
for this line : requester.makeRequest ... .then(function(city){
replace .then(function(city){ with var city = await requester.makeRequest , city will have the fulfilled value of the promise, do this for the rest of thens :
( keep in mind that await is only used inside an async function, you can use an iife )
(async () => {
  var city = await requester.makeRequest(`${geocode_url}?locate=${req.query.q}&json=1${geocode_token}`);
  var final_result = []
  var lat = city.latt;
  var long = city.longt;
  // request to get list of cities closer to that location,//takes latitude and longitude as parametersvar closer_cities = await requester.makeRequest(`${metaweather_url}?lattlong=${lat},${long}`);
  var cities_len = closer_cities.length;
  for (i = 0; i < closer_cities.length; i++) {
    woeid = closer_cities[i].woeid//request to get weather using woeid parametervar weather = await requester.makeRequest(woeid_url + woeid);
    var lattlong = weather.latt_long;
    var onwater = await requester.makeRequest(`${onwater_url}${lattlong}?access_token=${water_access_token}`);
    var temp = Object.assign(weather, onwater)
    final_result.push(temp)
    if (final_result.length == cities_len) {
      res.status(200).json({
        error: false,
        data: {
          message: final_result
        }
      })
    }
  }
})();
Solution 3:
then is misused in the first place because it results in callback hell. Promises are callback-based but they support chaining which is supposed to eliminate nested callbacks.
It should be:
  requester.makeRequest(geocode_url +`?locate=${req.query.q}&json=1` + geocode_token)
  .then(function(city){
    var final_result = []
    var lat = city.latt;
    var long = city.longt;
    return requester.makeRequest(metaweather_url + '?lattlong='
     + lat + ',' + long)
  })
  .then(function(closer_cities) {
     ...
  });
If there's a promise inside then, it should be returned. This way there's no more than a single level of callback nesting.
await is syntactic sugar for then, and rejections should be handled as well:
app.get('/search', function(req, res, next) {
  try {
    ...
    const city = await requester.makeRequest(geocode_url +`?locate=${req.query.q}&json=1`
      + geocode_token);
    var final_result = []
    var lat = city.latt;
    var long = city.longt;
    const closer_cities = await requester.makeRequest(metaweather_url + '?lattlong='
         + lat + ',' + long);
    ...
  } catch (err) {
    next(err)
  }
});
Solution 4:
When calling async functions you are not supposed to use .then(...) construct...
Simply let result = await myAsynchronousFunction(a, b, c); ...
Post a Comment for "Nodejs: How To Avoid Nested .then() When Using Async/await"