小编JPB*_*JPB的帖子

如何在 javascript 中使用 .reduce() 链接带有参数的 Promise/函数数组

我正在寻找使用reduce() 循环遍历返回promise 的函数数组。目标是将它们链接起来,以便它们等待当前迭代完成后再开始新的迭代。

这对我来说尤其令人困惑,因为我需要传递数组索引和另一个参数。

我知道这里和谷歌上有一些例子,但所有这些对我来说都解释得太抽象了,我无法理解它们的解释方式。

这是我的代码(编辑后现在可以工作):

getAllPostsInfo(maxNumberOfPosts)

.then((posts) => {                                                                      
    printIntroMsg(posts)
    var arrayOfFunctions = posts.map( () => {
        return main
    })

    arrayOfFunctions.reduce((p, fn, i) => {
    return p.then( () => {

        // you may customize what you pass to the next function in the chain
        // and you may accumulate prior results in some other data structure here
        return fn(posts, i);
    });
    }, Promise.resolve() )
        .then(result => {
            // all done here
        }).catch(err => {
            // error here
        });
}) …
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise

1
推荐指数
1
解决办法
2958
查看次数

标签 统计

javascript ×1

node.js ×1

promise ×1