2017-09-15 6 views
0

約束を使用して再帰的呼び出しを行う簡単な方法はありますか?ここに私のサンプルがあります。約束の退行的な呼び出し

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)を使用する必要があります。私はこのシナリオを得るためにのみ退行的な呼び出しを行う必要がありますが、私はより良い(Promise)方法を知りたいと思います。

大歓迎です。

+0

'Q'、あなただけの'新しい約束(...を) '使用することができ、そしてあなたがチェーンにあなたの要望を' async'/'await'を使用することができるための必要はありません'for(...) 'ループです。 – ideaboxer

+0

このシナリオでは、以前の呼び出しに基づいてforループを使用する方法は、次の呼び出しに進む必要があるかどうかを判断するか、解決する必要があります。 –

+0

私の答えを見てください。それは私が心に持っていたことを示しています。 – ideaboxer

答えて

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

+0

私はそれがうまくいくと思います。参照してください、よりよい方法はありますか?おかげで –

+0

"良い方法"とはどういう意味ですか? – ideaboxer

+0

私は他人からのより多くの提案を期待しました –

関連する問題