首页 > 解决方案 > 为什么此代码返回未定义以及如何使此代码工作

问题描述

向api请求成功,按预期返回数据。来自 api 的数据被保存到 'fact' 变量中。问题是 'getData' 函数返回预期会解析数据的承诺,而不是返回未定义的。


const getData = num => {
  let fact;
  if (Array.isArray(num)) {
    fetch(`http://numbersapi.com/${num[0]}/${num[1]}/date`)
      .then(response => response.text())
      .then(data => {
        fact = data;
      });
  } else if (num.math === true) {
    fetch(`http://numbersapi.com/${num.val}/math`)
      .then(response => response.text())
      .then(data => {
        fact = data;
      });
  } else {
    fetch(`http://numbersapi.com/${num}`)
      .then(response => response.text())
      .then(data => {
        fact = data;
      });
  }
  return new Promise((resolve, reject) => {
    resolve(fact);
  });
};

getData([1, 26]).then(val => {
  console.log(val);
});

标签: javascriptpromise

解决方案


Fetch 是一个基于 Promise 的 API,它返回一个 Promise,你不需要在 Promise 中包装 fetch。

您可以在 if 检查中准备 url 字符串,然后在 fetch 调用中使用它。

例子

const getData = num => {
  let url;
  if (Array.isArray(num)) {
    url = `http://numbersapi.com/${num[0]}/${num[1]}/date`;

  } else if (num.math === true) {
    url = `http://numbersapi.com/${num.val}/math`;

  } else {
    url = `http://numbersapi.com/${num}`
  }
  return fetch(url);
};

getData([1, 26]).then(response => {
  console.log(response.text());
});


推荐阅读