javascript - 递归循环一个 promise ?

标签 javascript node.js recursion callback es6-promise

我从 DigitalOcean API 获取 Droplet 列表,但 Droplet 列表是每页的。

响应为您提供该页面和下一页上的水滴列表...

我正在尝试递归地获取每个 promise 的下一页:

getDropletsPerPage(command,firstPage).then((response)=>{

    nextPage= response['nextPage']
    droplets= response['droplets']
​
    getDropletsPerPage(command, nextPage).then((response)=>{

        nextPage= response['nextPage']
        droplets= response['droplets']
​
        getDropletsPerPage(command, nextPage).then((response)=>{

            nextPage= response['nextPage']
            droplets= response['droplets']

            // Repeat until last page..
        })
    })
})

最佳答案

您可以使用递归:

const dispatcher = {
    page: firstPage,
    droplets: [],
    execute: function () {
        const self = this;
        return new Promise(function (resolve, reject) {
            getDropletsPerPage(command, this.page).then(function (response) {
                self.page = response['nextPage'];
                self.droplets = self.droplets.concat(response['droplets']);
                if (nextPage === LAST_PAGE) {
                    resolve(true);/* done */
                } else {
                    self.execute().then(function () {
                        resolve(true);
                    });
                }
            });
        });
    }
}
dispatcher.execute().then(function() {
    /* reached last page */
});

关于javascript - 递归循环一个 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58802388/

相关文章:

node.js - NodeJS 使用两个 IP 地址和相同的端口 443 在单个服务器上托管两个应用程序

algorithm - 如果记忆化是自上而下的深度优先,而 DP 是自下而上的广度优先,那么自上而下的广度优先/自下而上的深度优先等价物是什么?

javascript - 设置 "overflow-y element"的滚动位置

node.js - 将 mongoose 字符串模式类型默认值设为空白并使该字段可选

node.js - 使用 webpack 转译 Node 服务器和 socket.io

javascript - D3 按深度 trim 分层数据?

java - 如何避免使用通配符对继承的递归类进行强制转换?

Javascript style.left 为空字符串

javascript - 如何在 iFrame body 标记上设置 jQuery data() 并从 iFrame 内部检索它?

javascript - 如何获取按钮的值?