gpt4 book ai didi

javascript - 如何使用 Fetch(不是 ajax)将 Promise 的解析存储到变量中

转载 作者:行者123 更新时间:2023-11-30 08:24:34 24 4
gpt4 key购买 nike

以下代码运行良好,并将从网站获取的内容记录到控制台(输出一个已经为 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

我想将该提取的内容值存储在一个变量中供以后使用。

所以,当我改变时:

console.log(data);

到:

return data;

我得到一个未定义的。有帮助吗?

最佳答案

因为您在 getData 函数中使用 .catch,如果出现其他问题,您的函数也将解析 undefined。如果您想记录它,那么您需要将错误作为拒绝 promise 返回,以便调用者可以处理错误,而不是在 promise 解决时获得未定义的数据值。

你可以return Promise.reject("no 200 status code")表示拒绝,return response.json()表示resolve 如果你想添加 .then(x=>console.log(x)) 你仍然需要返回一些东西,否则调用 getData 的东西将解析为未定义:

getData = url => {
fetch(url)
.then(response => {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
return Promise.reject(//reject by returning a rejecting promise
"Looks like there was a problem. Status Code: " + response.status
);
}

// Examine the text in the response
response.json().then(data => {
console.log(data);
return data;//still need to return the data here
});
})
.catch(function (err) {
console.log("Fetch Error :-S", err);
//return the reject again so the caller knows something went wrong
return Promise.reject(err);
});
};

getData(urlToFetch) // logs to console the website call: a json file
.then(
x=>console.log("caller got data:",x)
)
.catch(
e=>console.log("caller got error:",e)
);

关于javascript - 如何使用 Fetch(不是 ajax)将 Promise 的解析存储到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47765757/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com