node.js pg-promise和来自API的分页

看看https://github.com/vitaly-t/pg-promise/wiki/Data-Imports有一个关于如何使用它进行导入的非常详细的文档。

但是,虽然这适用于演示场景,但我不知道如何将其应用于我的案例。

当我进行networking调用时,我得到了实际的JSON数据和标题中的一个参数,它给了我下一页的值(可以是date或string或数字值)。

在这个例子中,它说:

db.tx('massive-insert', t => { return t.sequence(index => { return getNextData(index) .then(data => { if (data) { const insert = pgp.helpers.insert(data, cs); return t.none(insert); } }); }); }) .then(data => { console.log('Total batches:', data.total, ', Duration:', data.duration); }) .catch(error => { console.log(error); }); 

在这种情况下, sequence(index将使用似乎增加+1的索引,但在我的情况下,

 function getNextData(nextPage) { //get the data for nextPage ..... //get the nextPage if exists for future use nextPage = response.next; resolve(data); } 

我的问题是,在这个例子中,我怎样才能用nextPagereplaceindex ,因为每个新的Promise需要使用前一个的nextPage

后来编辑:如果我想从一个特定的值nextPageInfo获取信息?

例如:

 db.any('Select value from table') .then(function(value) { var data = value; //not working db.tx('massive-insert', t => { return t.sequence((index, data) => { return getNextData(index, data) .then(a => { if (a) { const insert = pgp.helpers.insert(a.data, cs); return t.none(insert).then(() => a.nextPageInfo); } }) }); }) .then(data => { // COMMIT has been executed console.log('Total batches:', data.total, ', Duration:', data.duration); }) .catch(error => { // ROLLBACK has been executed console.log(error); }) } 

在这个问题之后,我用新的额外部分扩展了文章Data Imports ,这就给你提供了你需要的例子。 从文章复制的例子:

 function getNextData(t, index, nextPageInfo) { // t = database transaction protocol // NOTE: nextPageInfo = undefined when index = 0 return new Promise((resolve, reject) { /* pull the next data, according to nextPageInfo */ /* do reject(error) on an error, to ROLLBACK changes */ if(/* there is still data left*/) { // if whateverNextDetails = undefined, the data will be inserted, // but the sequence will end there (as success). resolve({data, nextPageInfo: whateverNextDetails}); } else { resolve(null); } }); } db.tx('massive-insert', t => { return t.sequence((index, data) => { return getNextData(t, index, data) .then(a => { if (a) { const insert = pgp.helpers.insert(a.data, cs); return t.none(insert).then(() => a.nextPageInfo); } }) }); }) .then(data => { // COMMIT has been executed console.log('Total batches:', data.total, ', Duration:', data.duration); }) .catch(error => { // ROLLBACK has been executed console.log(error); }); 

请注意,因为我们将getNextData的结果链接到nextPageInfo的值,所以如果它的值是undefined ,它将执行下一个插入,然后结束序列(成功)。