如何在fetch语句的.then()语句中的变量中存储数据? [英] How to store data in a variable in the .then() statement of a fetch statement?

查看:532
本文介绍了如何在fetch语句的.then()语句中的变量中存储数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试一种将第1行中收到的数据(在注释中提到)存储到一个变量中的方法,以后可以对其进行修改.

I have been trying to think of a way to store the data received in Line 1 (mentioned in comments) in to a variable that I can modify later on.

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));

推荐答案

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

You can store responses to another variable like this.

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

but You should use that with async/await because fetch() is async.

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

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

   //console.log(response); //store in response.
}

fetchData();

这篇关于如何在fetch语句的.then()语句中的变量中存储数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆