Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将数据存储在fetch语句的.then()语句中的变量中?_Javascript_Html - Fatal编程技术网

Javascript 如何将数据存储在fetch语句的.then()语句中的变量中?

Javascript 如何将数据存储在fetch语句的.then()语句中的变量中?,javascript,html,Javascript,Html,我一直在想一种方法,将第1行(注释中提到的)中接收到的数据存储到一个变量中,稍后我可以修改该变量 var requestOptions = { method: 'GET', redirect: 'follow' }; fetch("https://api.covid19api.com/live/country/south-africa", requestOptions) .then(response => response.text()) .then(re

我一直在想一种方法,将第1行(注释中提到的)中接收到的数据存储到一个变量中,稍后我可以修改该变量

var requestOptions = {
    method: 'GET',
    redirect: 'follow'
};

fetch("https://api.covid19api.com/live/country/south-africa", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result)) //Line 1
    .catch(error => console.log('error', error));

您可以像这样存储对另一个变量的响应

但是您应该将它与
async/await
一起使用,因为
fetch()
是异步的

var请求选项={
方法:“GET”,
重定向:“跟随”
};
异步函数fetchData(){
const response=等待获取(“https://api.covid19api.com/live/country/south-africa“,请求选项)
.then(response=>response.text())
.then(result=>{return result})//第1行
.catch(error=>console.log('error',error));
//console.log(response);//存储在响应中。
}

fetchData()您可以只执行
。然后(result=>myVariable=result)
。你过得更好。这能回答你的问题吗?我使用myVariable=fetchData()将其存储在变量中。这无疑将数据存储在myVariable中,但它也会在控制台上打印出来,这是我不想要的。“有办法吗?”阿迪我编辑了答案。如果您不想看到
console.log
,可以将其删除。谢谢,但我还面临一个问题。你能看看@jornsharpe吗?那我该怎么办呢?正如你所看到的@zynkn,jonsharpe在他的解决方案中使用了wait,但没有什么区别