如何使用 node-apac 链接多个寻呼请求?

How to chain multiple paging request with node-apac?

我是 Javascript 和 Nodejs 的新手,我正在尝试设置一个服务器,该服务器可以通过 node-apac 节点包从 amazon-product-api 请求多个 ItemPages。到目前为止,我的 http 服务器已启动,并且 运行 定义了一些路由。我还可以请求单个 ItemPage。但是我无法链接请求。

查询示例:

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

如您所见,我想从第一个请求中读取有多少项目页面可用于我的项目搜索,并为每个项目页面创建一个新请求。不幸的是 Promise.all(...).then() 从未被调用过。

感谢任何帮助

theQuery 看起来像一个对象。因此,当你执行 theQuery.ItemPage = i 然后你传递 theQuery 时,它通过指针传递,你将相同的对象传递给每个请求并且只是覆盖 ItemPage 属性 在那个对象上。这不太可能正常工作。

我不太清楚 theQuery 是什么,但您可能需要复制它。

此外,您还可以 return 来自 .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
});