【发布时间】:2019-02-06 18:00:30
【问题描述】:
以下代码运行良好,并将从网站获取的信息记录到控制台(输出已经为 json 格式的简单文件):
getData = url => {
fetch(url)
.then(response => {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
return; //returns undefined!
}
// Examine the text in the response
response.json().then(data => {
console.log(data);
});
})
.catch(function(err) {
console.log("Fetch Error :-S", err);
});
};
getData(urlToFetch); // logs to console the website call: a json file
我想将该 fetch 的内容值存储在一个变量中以供以后使用。
所以,当我改变时:
console.log(data);
到:
return data;
我得到一个未定义的。有什么帮助吗?
【问题讨论】:
-
你试过
getData(urlToFetch).then(x => console.log(x));吗?并在response之前添加return -
看起来您正在尝试同步获取异步结果
-
我认为你是对的@JaromandaX
return resolve(data)会修复它吗? -
以何种方式修复什么?您的代码中没有名为 resolve 的函数
标签: javascript promise response fetch