Error while using Request-Promise with Falcor

133 views Asked by At

I am trying to do a Falcor GET call to an external api using Request-Promise (rp) package. I am getting the response in "res" (line no.8) but I am not able to return it to the Falcor model path (line no.13). It gives a "Uncaught (in promise)" error.

Also, I tried to put the return statement (line 13) inside the then block (i.e.) after line 8. Then it give "GET http://localhost/getBusinessTypes... 500 (Internal Server Error)" error.

1) router.get('/getBusinessTypes.json', falcorServer.dataSourceRoute(function (req, res) {
2)    return new falcorRouter([
3)        {
4)            route: "businessTypes.all",
5)            get: function() {
6)                rp('http://localhost:8000/service?method=getBusinessTypes')
7)                    .then(function (res) {
8)                        console.log("Response from external Api: " + res);
9)                    })
10)                    .catch(function (err) {
11)                        console.log(err);
12)                    });
13)                return {path: ["businessTypes", "all"], value: $atom(res)};
14)            }
15)        }
16)    ]);
17) }));

Let me know what is missing here.

1

There are 1 answers

3
Steve Holgado On BEST ANSWER

Try returning the promise from the rp() call:

router.get('/getBusinessTypes.json', falcorServer.dataSourceRoute(function (req, res) {
  return new falcorRouter([{
    route: "businessTypes.all",
    get: function() {
      return rp('http://localhost:8000/service?method=getBusinessTypes')
        .then(function (res) {
          console.log("Response from external Api: " + res)
          return {
            path: ["businessTypes", "all"],
            value: $atom(res)
          }
        })
        .catch(function (err) {
          console.log(err)
          // Handle error
        })
    }
  }])
}))

You can use async/await like this:

router.get('/getBusinessTypes.json', falcorServer.dataSourceRoute(function (req, res) {
  return new falcorRouter([{
    route: "businessTypes.all",
    get: async function() {

      try {
        let result = await rp('http://localhost:8000/service?method=getBusinessTypes')

        console.log("Response from external Api: " + result)
        return {
          path: ["businessTypes", "all"],
          value: $atom(result)
        }
      }
      catch(err) {
        console.log(err)
        // Handle error
      }

    })
  }])
}))