在使用then或WAIT时,在express路由内获取api数据返回未定义

rmbxnbpk  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(282)

问题

我正在创建一个从api获取货币汇率的express服务器。在路由中,我通过一个helper函数获取这些汇率,然后我想在格式的响应体中返回它们 {data: rates, status: 200} .
然而,从路线返回的唯一东西是 {status: 200} 由于汇率未定义(待定)。获取成功,即未在catch子句中捕获,也未返回默认结果。它们还存在关键的“费率”。
我不明白为什么这是未定义的,也不知道如何修复它,因为我正在等待服务的响应,然后才从路线返回。我还尝试将路由器响应封装在 .then 子句而不是使用wait,但我遇到了同样的问题。

api服务获取

require("isomorphic-fetch");
const { DEFAULT_RATES } = require("../resources/other/default_exchange_rates");

// Documentation: https://currencyfreaks.com/documentation.html
let domain = "https://api.currencyfreaks.com/";

/*
 * Retrieve exchange rates from USD to other currencies.
 * Return object format: {EUR: "2.0293", XXX: "0.55736", ...}
 */

exports.getExchangeRates = async () => {
  return await (
    fetch(`${domain}latest?apikey=${process.env.EXCHANGE_RATE_API_KEY}`)
      .then((res) => {
        if (res.status > 200) {
          return DEFAULT_RATES;
        }
        let api_response = res.json();
        return api_response.rates; 
      })
      // Catch parse error
      .catch((err) => {
        console.log(err);
      })
  );
}

路线

const service = require("../services/currency_api");
const express = require("express");
const router = express.Router();

router.post("/", async (req, res) => {
  try {
    const rates = await service.getExchangeRates();
    return res.status(200).send({ data: rates, status: 200 });
  } catch (err) {
    console.log(err);
    return res.stats(400).send({ error: "An error occurred", status: 400 });
  }
});

module.exports = router;

/*
 Postman test response:
 {
   "status": 200
 }

* /
js5cn81o

js5cn81o1#

更改包含以下内容的回调:

let api_response = res.json();

致:

.then((res) => {
    if (res.status > 200) {
      return DEFAULT_RATES;
    }
    return res.json();

  })
  .then(api_response => api_response.rates);

这个
fetch response.json() 方法返回一个承诺,因此要获得实际值,您必须等待它,或者返回承诺并添加另一个 .then 等待 res.json() 解决。
反过来,当你不再等待 res.json() 你的诺言决定 undefined ( api_response 这是一个承诺,而且 ratesundefined ),然后 data 也是 undefined

5gfr0r5j

5gfr0r5j2#

使用baldrs答案的工作解决方案

exports.getExchangeRates = () =>{
  let url = `${domain}latest?apikey=${process.env.EXCHANGE_RATE_API_KEY}`;
  return (
    fetch(url)
      .then((res) => {
        if (res.status > 200) {
          return DEFAULT_RATES;
        }
        return res.json();
      })
      .then((data) => data.rates)

      .catch((err) => {
        console.log(err);
      })
  );
}

相关问题