带有fetch的函数返回undefined而不是数组(React Native)

时间:2019-12-10 05:12:44

标签: javascript reactjs react-native asynchronous fetch

我有一个具有某些功能的文件:

const API = {
async getComments() {
   var data = [];
   var url = 'http://url.com/wp-json/wp/v2/comments';
   const serviceResponse = await fetch(
    url,
    )
    .then((serviceResponse) => {
     return serviceResponse.json();
   } )
    .catch((error) => console.warn("fetch error:", error))
    .then((serviceResponse) => {
      for (i in serviceResponse) {
        data.push({
         "key": serviceResponse[i]['id'].toString(),
         "name": serviceResponse[i]['author_name'],
         "content": serviceResponse[i]['content']['rendered'].replace(/<(.|\n)*?>/g, ''),
         "gravatar": serviceResponse[i]['author_avatar_urls']['96'],
         "date": serviceResponse[i]['date'].replace('T', ' ')
        });
      }
      global.comments = data;
      return data;
   });
 }
}

export { API as default }

在另一个文件中,我包括该文件,并进行呼叫:

var comments = await API.getComments(key);
console.log (comments);

但是我收到未定义的信息,我试图用bind创建一个函数: this.newGetComments = API.getComments.bind(this);结果相同。我使用了全局变量,但我想删除全局变量。

3 个答案:

答案 0 :(得分:0)

异步函数总是返回一个promise,因为您没有从getComments方法返回任何内容,该函数自动解析并返回undefined(Promise.resolve(undefined))。您需要从getComments方法返回serviceResponse以获得获取api的响应。

答案 1 :(得分:0)

/* Few suggestions;
1. you  are not returning anything from the getComments method. Please return fetch(url) response.
2. you should return  something from the catch block to handle the error.
*/


const API = {
  async getComments() {
    var url = 'http://url.com/wp-json/wp/v2/comments';
    var response = await fetch(url)
      .then(serviceResponse => {
        return serviceResponse.json();
      })
      .then(serviceResponse => {
        let data = [];
        
        // rest of your code.
        
        return { success: true, data };
      })
      .catch(error => {
        console.warn('fetch error:', error);
        return { success: false, error };
      });
    return response
  },
};

var comments = await API.getComments(key);
if (comments.success) {
  // handle the success case  comments.data
} else {
  // handle the Error case  comments.error
}

console.log(comments);

答案 2 :(得分:0)

您可以尝试以下操作:

async componentDidMount() {
   let data = [];
   const result = await this.getComments();
   const jsonData = await result.json();
   console.log('Result ==> ', jsonData.serviceResponse);

   jsonData.serviceResponse.map(data => 
      data.push({
                 "key": data['id'].toString(),
                 "name": data[i]['author_name'],
                 "content": data[i]['content']['rendered'].replace(/<(.|\n)*?>/g, ''),
                 "gravatar": data[i]['author_avatar_urls']['96'],
                 "date": data[i]['date'].replace('T', ' ')
               })
   );
   console.log('Data ==> ', data);
}

async getComments() {
   const result = await fetch('http://url.com/wp-json/wp/v2/comments', {method: 'GET'});
   return result;
}