javascript - 为什么此代码返回未定义以及如何使此代码工作
问题描述
向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);
});
解决方案
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());
});
推荐阅读
- python - C++ & Python:格式化数组项并从中删除重复项
- javascript - 算法:这个问题我怎么不能使用滑动窗口方法?
- python - 如何将多个函数应用于单个 DataFrame 列?
- reactjs - React,如果索引大于数组长度,如何在索引0处返回
- python-3.x - Stretch to buster : 如何解决不一致的问题
- typescript - 强制多个回调具有相同的输入类型而不手动传递泛型
- firebase - 在 nullsafety 之后使用带有 json_serializable 的 firestore
- firebase - Firestore 触发器永远不会调用
- asp.net-mvc - log4net.LogicalThreadContext.Properties["UserId"] 被操纵
- unity3d - 在 Unity 中围绕地球形状的椭球体表面移动