簡體   English   中英

使用 request-promise 的嵌套異步請求

[英]Nested async requests using request-promise

我正在使用 Visual Studio Online API 並嘗試通過存儲庫獲取分支統計信息。 為此,我嵌套了異步調用。 我正在使用request-promise來解決我的 GET 請求。

我遇到的問題是了解如何在所有分支都添加到頂級 model 后返回 model:

當我 console.log 結果我得到[]顯然因為它沒有解決分支請求。

 var model = []; rp(options).then(function(repos) { repos.value.forEach(function(repository) { var repo = { id: repository.id, name: repository.name, branches: [] }; var branchOptions = options; branchOptions.url = config.endPoints.base + config.endPoints.branches(repository.id); rp(branchOptions).then(function(branches) { branches.value.forEach(function(branch) { repo.branches.push({ name: branch.name, behind: branch.behindCount, ahead: branch.aheadCount }); }) }).then(function() { model.push(repo); }); }); }).finally(function(){ console.log(model); res.json(model); });

我試圖在 foreach 之后添加一個.then()但顯然forEach不會返回 promise。

有任何想法嗎? 我已經編程了 14 個小時,所以對我來說沒有任何意義哈哈。

下面應該解決您的問題,而不是執行forEach循環,而是在您的 promise 鏈中將其替換為.map() 我也在你的內部 promise 中完成了這個。 此外,我已經讓內部 promise 在完成后返回,因此外部 map 知道每次迭代何時完成。

我離開了.finally() ,因為這表明無論填充model的結果如何,我們都希望始終響應用戶。

我還建議將.catch()添加到您的外部和內部承諾中,以確保您正確處理任何錯誤。 就目前而言,如果發生錯誤,則不會處理它,並且將返回model並且您永遠不會知道在內部或外部承諾上的.map()迭代中發生了錯誤。

另外值得注意的是request-promise使用bluebird實現了 A+ Promises。

 var model = []; rp(options).map(function(repository) { var repo = { id: repository.id, name: repository.name, branches: [] }; var branchOptions = options; branchOptions.url = config.endPoints.base + config.endPoints.branches(repository.id); return rp(branchOptions).map(function(branch){ repo.branches.push({ name: branch.name, behind: branch.behindCount, ahead: branch.aheadCount }); }).then(function() { model.push(repo); }); }).finally(fuction() { console.log(model); return res.json(model); });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM