提取后如何返回结果?

时间:2018-08-29 03:06:33

标签: javascript json asynchronous async-await fetch

任务是向图像API(pixabay)发出异步请求并返回数据。我正在尝试使用访存来实现,对吗?但是在这种情况下,我得到的返回值为空。我该怎么办?

function myfunc(){
  fetch(URL).then(function(response) {
      return response.json();
  }).then(function(hitsJSON) {
      hitsJSON.hits.forEach(item => {
          let resultItem = {
              id: item.id,
              url: item.previewURL,
              tags: item.tags
          }
          results.push(resultItem);
      });
  });
  return {
      query: query,
      images: results
  };
 }

1 个答案:

答案 0 :(得分:0)

您可以通过扩展在myfunc()中使用promise的方式来返回获取请求的结果。

通常的方法是从fetch()返回myfunc()创建的承诺。这样,当您调用myfunc()时,可以将一个函数处理程序添加到.then()中,该处理程序将在请求完成后被执行(带有获取结果):

function myfunc(){

  // Add return here to return the fetch's promise
  return fetch(URL).then(function(response) {
      return response.json();
  }).then(function(hitsJSON) {

      var results = []

      hitsJSON.hits.forEach(item => {
          let resultItem = {
              id: item.id,
              url: item.previewURL,
              tags: item.tags
          }
          results.push(resultItem);
      });

      // Return result here when request is complete
      return {
          query: 'query',
          images: results
      };
  });
 }


 // Use myfunc() like this:    
 myfunc().then( function( results ) {

   console.log(results)

 })