0

I am writing code to add the data corresponding to each row in my json data. All functions and code writing are complete. When all the data has been called, it should return to json. But before all the code is executed it returns json. So even though all the code runs fine, json always returns an empty value. Please advise.

var request = require('request');
var axios = require('axios');

router.get('/geometric/getAddress', async (req, res) => {
    let confmKey = "secret";
    let resultType = "json";
    let countPerPage = "10"

    let page = appjs.vCheck(req.query.page, "");
    let kw = appjs.vCheck(req.query.keyword, "");

    var stmt = "http://10.10.100.12:8080/addr.do?";
    stmt = stmt + "currentPage=" + page; 
    stmt = stmt + "&countPerPage=" + countPerPage;
    stmt = stmt + "&resultType=" + resultType;
    stmt = stmt + "&confmKey=" + confmKey;
    stmt = stmt + "&keyword=" + qs.escape(kw)

    request(stmt, async (err, result) => {
        if (err) throw err;

        const con = JSON.parse(result.body);
        const juso = con.results.juso;


        var dd = ""
        let res_data = juso.map(async (addr) => {
            let admCd = appjs.vCheck(addr.admCd, "");
            let rnMgtSn = appjs.vCheck(addr.rnMgtSn, "");
            let udrtYn = appjs.vCheck(addr.udrtYn, "");
            let buldMnnm = appjs.vCheck(addr.buldMnnm, "");
            let buldSlno = appjs.vCheck(addr.buldSlno, "");

            axios.post("http://localhost:3001/web/api/geometric/coordinates",
                {
                    admCd : admCd,
                    rnMgtSn : rnMgtSn,
                    udrtYn : udrtYn,
                    buldMnnm : buldMnnm,
                    buldSlno : buldSlno
            }).then((d) => {
                return {
                    "roadAddr" : d.roadAddr,
                    "jibunAddr" : roadAddr,
                    "zipNo" : d.roadAddr,
                    "longitude" : roadAddr,
                    "latitude" : d.roadAddr
                }
            })
        })

        let aa = await Promise.all(res_data)
        res.json(aa)
    })
});
Andrew Regan
  • 5,087
  • 6
  • 37
  • 73
Tae Hun Yu
  • 39
  • 7

2 Answers2

0

This is happening because you don't return any promise from the map callback. You should do something like this:

let res_data = juso.map(async (addr) => {
  let admCd = appjs.vCheck(addr.admCd, "");
  let rnMgtSn = appjs.vCheck(addr.rnMgtSn, "");
  let udrtYn = appjs.vCheck(addr.udrtYn, "");
  let buldMnnm = appjs.vCheck(addr.buldMnnm, "");
  let buldSlno = appjs.vCheck(addr.buldSlno, "");

  return axios.post("http://localhost:3001/web/api/geometric/coordinates",
    {
      admCd : admCd,
      rnMgtSn : rnMgtSn,
      udrtYn : udrtYn,
      buldMnnm : buldMnnm,
      buldSlno : buldSlno
     })
   })

let aa = (await Promise.all(res_data)).map(({data: d}) => ({
  "roadAddr" : d.roadAddr,
  "jibunAddr" : roadAddr,
  "zipNo" : d.roadAddr,
  "longitude" : roadAddr,
  "latitude" : d.roadAddr
}));

res.json(aa)
Vasileios Pallas
  • 4,801
  • 4
  • 33
  • 50
0

Since you are not returning any promise from the map function, the await Promise.all(res_data) is trivial code.

UPDATE:

  • Axios library returns full-fledged promise so can be simply returned from the map callback.
  • Then those returned promises can be awaited and mapped to desired result.
  let res_data = juso.map(async addr => {
  let admCd = appjs.vCheck(addr.admCd, "");
  let rnMgtSn = appjs.vCheck(addr.rnMgtSn, "");
  let udrtYn = appjs.vCheck(addr.udrtYn, "");
  let buldMnnm = appjs.vCheck(addr.buldMnnm, "");
  let buldSlno = appjs.vCheck(addr.buldSlno, "");

  return axios.post("http://localhost:3001/web/api/geometric/coordinates", {
    admCd: admCd,
    rnMgtSn: rnMgtSn,
    udrtYn: udrtYn,
    buldMnnm: buldMnnm,
    buldSlno: buldSlno
  });
});

Then await for those promises returned (better with try/catch for any of those failed promises OR Promise.all(res_data).then().catch(e) to handle errors too):

await Promise.all(res_data)
  .then(resolvedPromises => {
    const aa = resolvedPromises.map(d => ({
      roadAddr: d.roadAddr,
      jibunAddr: d.roadAddr,
      zipNo: d.roadAddr,
      longitude: d.roadAddr,
      latitude: d.roadAddr
    }));

    return res.json(aa);
  })
  .catch(e => {
    //handle error because one of those axios promises failed: e.message
  });
ambianBeing
  • 3,449
  • 2
  • 14
  • 25
  • 1
    No, [not "like this"](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Sep 07 '19 at 14:30
  • @Bergi I understand `axios` does return promise and wrapping promise in promise is bad and would have been simpler to return it. Probably not in this case though the way code is written. Here `catch(e)` handler with `reject` at axios would indeed bubble up error as rejection to `Promise.all`. What'd I miss? – ambianBeing Sep 07 '19 at 14:46
  • Yes, just returning the promise would have been much simpler and would work the same. Not sure what you mean about rejections bubbling up, how do you think the antipattern code works differently? – Bergi Sep 07 '19 at 14:56
  • @Bergi Thanks for the link it cleared up a couple of things. My takeaway was when one doesn't handle error within inner `async` code (in this case `axios`) because `then` really works like chain. But here any of those `axios` error would get caught in `catch(e)` and passed on to `reject` callback.. I am really wondering what could go wrong here? – ambianBeing Sep 07 '19 at 15:09
  • 1
    Yes, you didn't forget to catch the inner errors and reject the outer promise, so this is good, but it's still totally overcomplicated code that should be simplified. The promise constructor antipattern is still makes for very error-prone code, even if implemented correctly. – Bergi Sep 07 '19 at 15:15
  • @Bergi Yeah! What you said makes absolute sense. Fairly new to SO. Should I delete this answer coz the other answer probably is better. – ambianBeing Sep 07 '19 at 15:20
  • 1
    I'd recommend that you [edit] your own answer to remove the promise antipattern - the rest of the answer, especially the explanation, is still fine -, and that you upvote all other answers that you consider to be good. – Bergi Sep 07 '19 at 15:22