[英]How to chain multiple paging request with node-apac?
我是Java和Nodejs的新手,我正在嘗試設置一個服務器,該服務器可以通過node-apac節點包從amazon-product-api請求多個ItemPage。 到目前為止,我的http服務器已經啟動並正在運行,並定義了一些路由。 我還可以請求一個ItemPage。 但是我很難鏈接請求。
Query的示例:
var query = {
Title: theTitle,
SearchIndex: 'Books',
BrowseNodeId: '698198',
Power: 'binding:not (Kindle or Kalender)',
Sort: '-publication_date',
ResponseGroup: 'ItemAttributes,Images',
ItemPage: 1
};
編碼:
AmazonWrapper.prototype.getAllPagesForQuery = function(theMethod, theQuery, theResultCallback) {
client.execute(theMethod, theQuery).then(function(theResult) {
var pageCount = theResult.result.ItemSearchResponse.Items.TotalPages;
var requests = [];
for(var i = 2; i < pageCount; i++) {
theQuery.ItemPage = i;
requests.push(client.execute(theMethod, theQuery));
}
Promise.all(requests).then(function(theResults) {
var data = theResults[0];
for(var i = 1; i < theResults.length; i++) {
var items = theResults[i].result.ItemSearchResponse.Items.Item;
data.result.ItemSearchResponse.Items.Item.concat(items);
}
theResultCallback(data);
});
});
};
如您所見,我想從第一個請求中讀取多少個Itempage可供我的ItemSearch使用,並為每個Itempage創建一個新請求。 不幸的是Promise.all(...)。then()從未被調用。
任何幫助表示贊賞
theQuery
看起來像一個對象。 這樣,當您執行theQuery.ItemPage = i
並隨后傳遞theQuery
時,它將通過指針傳遞給您,您是將相同的對象傳遞給每個單個請求,而只是覆蓋該對象上的ItemPage
屬性。 這不太可能正常工作。
我不知道確切是什么theQuery
,但是您可能需要復制它。
同樣,您最好從.getAllPagesForQuery()
返回一個.getAllPagesForQuery()
而不要使用回調,因為您已經在使用.getAllPagesForQuery()
。 通過promise,錯誤處理和鏈接非常容易。
您沒有完全披露足夠的代碼,但是以下是有關解決方法的一般想法:
AmazonWrapper.prototype.getAllPagesForQuery = function(theMethod, theQuery) {
return client.execute(theMethod, theQuery).then(function(theResult) {
var pageCount = theResult.result.ItemSearchResponse.Items.TotalPages;
var requests = [];
for(var i = 2; i < pageCount; i++) {
// make unique copy of theQuery object
var newQuery = Object.assign({}, theQuery);
newQuery.ItemPage = i;
requests.push(client.execute(theMethod, newQuery));
}
return Promise.all(requests).then(function(theResults) {
var data = theResults[0];
for(var i = 1; i < theResults.length; i++) {
var items = theResults[i].result.ItemSearchResponse.Items.Item;
data.result.ItemSearchResponse.Items.Item = data.result.ItemSearchResponse.Items.Item.concat(items);
}
return data;
});
});
};
// Usage example:
obj.getAllPagesForQuery(...).then(function(data) {
// process returned data here
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.