javascript - 如何在 Node.js 中实现递归 Promise 调用

标签 javascript node.js recursion promise

我正在调用一个 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/

相关文章:

javascript - 无法在 Angular 4 中绑定(bind)属性

javascript - json 字符串没有转换成对象

node.js - 如何先创建目录,然后通过node js中的multer上传该目录上的图像

javascript - 类型错误 : Class extends value undefined is not a constructor or null

javascript - Jasmine spy : How to make it work when the spyed function reference is passed?

javascript - react : Child Prop inside Map Function

node.js - 错误状态 Unable to require(node_modules/prisma/libquery_engine-debian-openssl-1.1.x.so.node) while npx performing prisma generate

php - 将函数从递归转换为迭代

recursion - 动态规划: Tabular vs memoization

c# - 递归边搜索