我正在调用一个 API,每个请求只能获取 1000 条记录, 我能够使用递归来实现这一点。
我现在正在尝试使用 Promise 来实现相同的目标,我对 Node.js 和 JavaScript 也相当陌生。
我尝试在 if else block 中添加递归代码,但失败了
var requestP = require('request-promise');
const option = {
url: 'rest/api/2/search',
json: true,
qs: {
//jql: "project in (FLAGPS)",
}
}
const callback = (body) => {
// some code
.
.
.//saving records to file
.
//some code
if (totlExtractedRecords < total) {
requestP(option, callback).auth('api-reader', token, true)
.then(callback)
.catch((err) => {
console.log('Error Observed ' + err)
})
}
}
requestP(option).auth('api-reader', token, true)
.then(callback)
.catch((err) => {
console.log('Error Observed ' + err)
})
我想使用 Promise 并以同步方式执行该方法, 即我想等到记录全部导出到文件并继续我的代码
最佳答案
我认为最好创建自己的 promise ,并在完成递归后简单地解决它。这是一个简单的例子,仅供您理解该方法
async function myRecursiveLogic(resolveMethod, ctr = 0) {
// This is where you do the logic
await new Promise((res) => setTimeout(res, 1000)); // wait - just for example
ctr++;
console.log('counter:', ctr);
if (ctr === 5) {
resolveMethod(); // Work done, resolve the promise
} else {
await myRecursiveLogic(resolveMethod, ctr); // recursion - continue work
}
}
// Run the method with a single promise
new Promise((res) => myRecursiveLogic(res)).then(r => console.log('done'));
关于javascript - 如何在 Node.js 中实现递归 Promise 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57803818/