承诺的回归呼唤

时间:2017-09-15 16:22:00

标签: node.js promise q

有没有简单的方法可以使用promise进行递归调用。这是我的样本。

function getData() {
   var result=[];
   var deferred = Q.defer();
   (function fetchData(pageno){
     var options = {
        method : 'GET',
        url : 'example.com/test',
        qs:{
          pageNo: pageno
        }
     }

    request(options, function (error, response, body) {
        if (error)throw new Error(error);

        if (body.hasMorePage == true) { //checking is there next page 
            result.push(body)
            fetchData(++body.pageno); // getting next page data
        } else {
             deferred.resolve(result); // promise resolve when there is no more page
        }
    });
   })(0);
    return deferred.promise;
}


getData().then(function(data){
     console.log(data)
});

让我们考虑API在连续调用中提供更多数据。为了收集所有数据,我需要使用前一个调用响应中的一些参数(EX:hasMorePage)。我只需要进行回归调用以获得这种情况,但我想知道更好的(承诺)方式。

最受欢迎。

1 个答案:

答案 0 :(得分:0)



async function request(options, callback) {
  // simulate server response of example.com/test with 1 second delay
  const totalNumberOfPages = 3;
  const pageNo = options.qs.pageNo;
  await new Promise(resolve => setTimeout(resolve, 1000));
  const hasMorePages = pageNo < totalNumberOfPages;
  const body = { hasMorePages };
  callback(void 0, { body }, body);
}


function getPage(pageNo) {
  const options = {
    method: 'GET',
    url: 'example.com/test',
    qs: { pageNo }
  };
  return new Promise(resolve => request(options, (error, response, body) => {
    console.log('response received', response);
    if(error) {
      throw new Error(error);
    }
    resolve(body);
  }));
}

async function getData() {
    const result = [];
    for(let i = 1, hasMorePages = true; hasMorePages; i++) {
        const body = await getPage(i);
        result.push(body);
        hasMorePages = body.hasMorePages;
    }
    return result;
}

getData().then(data => console.log('RESULT', data));
&#13;
&#13;
&#13;