如何在JS FETCH API外部访问返回值

时间:2019-11-09 08:05:33

标签: javascript reactjs typescript ionic-framework

我是Typescript React和Ionic框架的新手。

我正在使用JS FETCH API并从第三方获取数据。现在,我想获取提取的数据并将其返回到我的DOM,但是我不知道如何在“提取”之外访问提取的数据。

请赐教。.谢谢

function getData() {
fetch('URL')
.then(response => {
return response.json();
}).then(data_from_fetched => {
let data = data_from_fetched.results;
return data;
}}

let data = getData()
console.log(data); //undefined

让数据= getData()   console.log(data); //未定义

我也尝试过这种异步方式。

async function getData() {
fetch('url')
.then(response => {
return response.json();
}).then(data_from_fetched => {
console.log(data_from_fetched)
let data = data_from_fetched.results;
return data;        
})

}

getData()。then(data => console.log(data));

或这个..

function getData() {
fetch('url')
.then(response => {
return response.json();
}).then(data_from_fetched => {
console.log(data_from_fetched)
let data = data_from_fetched.results;
return data;        
})
}

let data= getData();
  

//并显示在我的DOM上

{movies.map(movie => movie){
let title = <IonCardTitle>{movie.title}</IonCardTitle>}}

1 个答案:

答案 0 :(得分:0)

您需要从getData函数返回一个Promise,您可以这样做

function getData() {
  return new Promise((resolve, reject) => {
    fetch('URL')
     .then(response => {
       return response.json();
      }).then(data_from_fetched => {
         let data = data_from_fetched.results;
         resolve(data);
   }
})    
}

然后您可以这样称呼它

let movies = '';
getData().then(data => {
  movies = data
});

希望有帮助