【问题标题】:Error while using Request-Promise with Falcor将 Request-Promise 与 Falcor 一起使用时出错
【发布时间】:2018-03-02 17:24:14
【问题描述】:

我正在尝试使用 Request-Promise (rp) 包对外部 api 进行 Falcor GET 调用。我在“res”(第 8 行)中得到响应,但我无法将其返回到 Falcor 模型路径(第 13 行)。它给出了一个 "Uncaught (in promise)" 错误。

另外,我尝试将 return 语句(第 13 行)放在第 8 行之后的 then 块(即)内。然后它给出 "GET http://localhost/getBusinessTypes... 500 (Internal Server 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) }));

让我知道这里缺少什么。

【问题讨论】:

    标签: falcor request-promise falcor-router


    【解决方案1】:

    尝试从 rp() 调用中返回承诺:

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

    【讨论】:

    • 只是出于好奇使用 Async/Await - 我可以在这个例子中使用它吗?你能指导我怎么做吗?
    • 我在我的答案中添加了一个 async/await 版本。我希望这会有所帮助。
    • 是的,它奏效了,而且更容易理解。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-09-27
    • 2016-07-03
    • 1970-01-01
    • 2017-06-25
    • 2020-06-22
    • 2018-01-14
    • 2015-12-08
    • 2021-01-25
    相关资源
    最近更新 更多