.then-callback 返回"undefined",但日志记录显示正确的输出



我正在尝试进行API调用以获取json对象以填充下拉菜单。当调用方法.getAllCurrency((时,它返回'undefined'。如果我用一个简单的控制台替换 jsonRes 的 return 语句.log(jsonRes(,它会显示正确的数据。

const apiKey = process.env.REACT_APP_API_KEY;
const baseURI = 'http://apilayer.net/api/live?access_key=';
const CurrencyLayer = {
  getAllCurrencies() {
    fetch(`${baseURI}${apiKey}`, )
    .then(res => res.json())
    .then(jsonRes => {
      return jsonRes
    })
    .catch(err => {
      console.log(err)
    })
  },
}
export default CurrencyLayer;

我没有收到任何错误消息。为什么会这样(对我来说(?;)

const CurrencyLayer = {
  getAllCurrencies() {
    return fetch(`${baseURI}${apiKey}`)
    .then(res => res.json())
    .catch(err => {
      console.log(err)
    })
  },
}

那里。
错误是:

  1. 您没有从函数返回由fetch生成的承诺。
  2. 无需特殊块即可返回res.json() .这个匿名函数已经隐式返回结果:res => res.json(),相当于:
res => {
    return res.json();
}

最新更新