想要改进这个问题?通过编辑这篇文章添加细节并澄清问题。
我可以使用以下函数将API转换为对象并打印出来:
function covertApiTobj(){
fetch('https://api.chucknorris.io/jokes/random?category=dev')
.then(res => res.json())
.then(data => console.log(data));}
但是我如何创建另一个变量,让它等于从API转换的对象,类似这样:
function covertApiTobj(){
fetch('https://api.chucknorris.io/jokes/random?category=dev')
.then(res => res.json())
.then(data => console.log(data));
const newdata = fetch('https://api.chucknorris.io/jokes/random?category=dev')
.then(res => res.json())
}
您可以使用promise链接。这是一个例子:
let apiUrl = 'https://api.chucknorris.io/jokes/random?category=dev';
let jsonData;
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.json();
})
.then(data => {
jsonData = data;
console.log('JSON data saved:', jsonData);
})
.catch(error => {
console.error('Error fetching data:', error);
});
您需要创建Promise
来传递对新变量的获取响应,然后在
结果,如下所示:async
函数中等待
let getData = async() => {
return fetch('https://api.chucknorris.io/jokes/random?category=dev')
.then(res => res.json())
.then(res => res)
.catch(err => err);
}
(async () => {
let data = await getData();
let newdata = await getData();
console.log('data:',data);
console.log('newdata:',newdata);
})();