Nodejs: How to avoid nested .then() when using async/await

Nikhil

Following is what I'm trying to do this in nodejs. The Rest API takes a city name as an input. I am trying to get the latitude and longitude using the geocode API for the input city. then, using the latitude and longitude, I am trying to get a list of closest cities using another API. then, for all those cities, I am getting the weather report, then for those cities, I am getting whether there is water and I am returning this back as a JSON.

As you can see, there is a lot of then and the goal of this exercise is to avoid nested callbacks.

I am using async/await which is supposed to have eliminated the nested then functions. But I don't see another way of doing this. The complete code snippet is below. The ugly part I am trying to fix is requester.makeRequest()

Following is just a snippet of the necessary code and not the complete working code. Any help on how to untangle this would be greatly appreciated.

app.get('/search', function(req, res, next) {
  const requester = {
      lastRequest: new Date(),
      makeRequest: async function(url) {
        const response = await fetch(url);
        const json = await response.json();
        return json;
      }
  };

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;
    // request to get list of cities closer to that location,
    //takes latitude and longitude as parameters
    requester.makeRequest(metaweather_url + '?lattlong='
     + lat + ',' + long)
    .then(function(closer_cities) {
      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
        requester.makeRequest(woeid_url + woeid)
        .then(function(weather) {
          var lattlong = weather.latt_long;
          requester.makeRequest(onwater_url+ lattlong +
          '?access_token=' + water_access_token)
          .then(function(onwater) {
            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}})
            }
          })
        })
       }
      })
    })
  })
Taki

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 parameters
  var 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
    var 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
        }
      })
    }
  }

})();

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to avoid nested promises?

分類Dev

How to avoid coupling when using useReducer?

分類Dev

How to avoid deep nested callback?

分類Dev

How to avoid slow collapse when using bootstrap collapse and div in a table

分類Dev

How to avoid pylint not-an-iterable when using a custom property class

分類Dev

How to Avoid Recreating Object When Using Let with LINQ

分類Dev

How to avoid using a var when doing multiple string replacements in a string

分類Dev

Trouble using nested callbacks in NodeJS

分類Dev

NodeJSとAWSLambdaでのAsyncAwaitの問題

分類Dev

Avoid showing UIAlertView when using PFLogInViewController

分類Dev

How to avoid warning about no return expression when using static_assert?

分類Dev

How to avoid "Invalid byte sequence" when looking for link with text using Nokogiri

分類Dev

How to avoid dropping items when using core.async pub/sub?

分類Dev

How do I avoid absolute pathnames in my code when using Git?

分類Dev

How can I avoid nested Navigation Bars in SwiftUI?

分類Dev

How to avoid duplicate using Mongodb c++

分類Dev

How to avoid using a return statement in a for-in loop?

分類Dev

Assert in MongoDB 3.6 NodeJS driver? And how to use assert when using promise implementation?

分類Dev

How do I set the exception type in Application Insights when raising an error using the NodeJS SDK?

分類Dev

Why does C# compiler create private DisplayClass when using LINQ method Any() and how can I avoid it?

分類Dev

How to filter nested object when using include Entity Framework core 3.1

分類Dev

In Rails, how can I reliably look for a specific parameter when using nested routes?

分類Dev

How to use ng-class on a top level container when using nested views

分類Dev

404 error when Routing using Express and Nodejs

分類Dev

'dependent name is not a type' when using nested nested class in templated class

分類Dev

NodeJS、asyncawaitから戻り値を取得します

分類Dev

Best way to avoid output truncation when using IJulia-notebook

分類Dev

Avoid using nested loops to find the max-sized sub-string of an array?

分類Dev

How to check for NULL when mapping nested JSON?

Related 関連記事

  1. 1

    How to avoid nested promises?

  2. 2

    How to avoid coupling when using useReducer?

  3. 3

    How to avoid deep nested callback?

  4. 4

    How to avoid slow collapse when using bootstrap collapse and div in a table

  5. 5

    How to avoid pylint not-an-iterable when using a custom property class

  6. 6

    How to Avoid Recreating Object When Using Let with LINQ

  7. 7

    How to avoid using a var when doing multiple string replacements in a string

  8. 8

    Trouble using nested callbacks in NodeJS

  9. 9

    NodeJSとAWSLambdaでのAsyncAwaitの問題

  10. 10

    Avoid showing UIAlertView when using PFLogInViewController

  11. 11

    How to avoid warning about no return expression when using static_assert?

  12. 12

    How to avoid "Invalid byte sequence" when looking for link with text using Nokogiri

  13. 13

    How to avoid dropping items when using core.async pub/sub?

  14. 14

    How do I avoid absolute pathnames in my code when using Git?

  15. 15

    How can I avoid nested Navigation Bars in SwiftUI?

  16. 16

    How to avoid duplicate using Mongodb c++

  17. 17

    How to avoid using a return statement in a for-in loop?

  18. 18

    Assert in MongoDB 3.6 NodeJS driver? And how to use assert when using promise implementation?

  19. 19

    How do I set the exception type in Application Insights when raising an error using the NodeJS SDK?

  20. 20

    Why does C# compiler create private DisplayClass when using LINQ method Any() and how can I avoid it?

  21. 21

    How to filter nested object when using include Entity Framework core 3.1

  22. 22

    In Rails, how can I reliably look for a specific parameter when using nested routes?

  23. 23

    How to use ng-class on a top level container when using nested views

  24. 24

    404 error when Routing using Express and Nodejs

  25. 25

    'dependent name is not a type' when using nested nested class in templated class

  26. 26

    NodeJS、asyncawaitから戻り値を取得します

  27. 27

    Best way to avoid output truncation when using IJulia-notebook

  28. 28

    Avoid using nested loops to find the max-sized sub-string of an array?

  29. 29

    How to check for NULL when mapping nested JSON?

ホットタグ

アーカイブ