簡體   English   中英

將請求承諾與Falcor一起使用時出錯

[英]Error while using Request-Promise with Falcor

我正在嘗試使用Request-Promise(rp)包對外部api進行Falcor GET調用。 我在“ res”(第8行)中得到響應,但無法將其返回到Falcor模型路徑(第13行)。 它給出了一個“未捕獲(承諾)”錯誤。

另外,我嘗試將return語句(第13行)放在第8行之后的then塊(即)內。然后給出“ GET http:// localhost / getBusinessTypes ... 500(內部服務器錯誤)”錯誤。

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) }));

讓我知道這里缺少什么。

嘗試從rp()調用返回promise:

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
        })
    }
  }])
}))

您可以像這樣使用async / await:

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
      }

    })
  }])
}))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM