Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用Q.all()时的瓶颈问题_Node.js_Es6 Promise_Q - Fatal编程技术网

Node.js 使用Q.all()时的瓶颈问题

Node.js 使用Q.all()时的瓶颈问题,node.js,es6-promise,q,Node.js,Es6 Promise,Q,我不熟悉nodeJS和promises,也不熟悉使用qpromise库。我面临的情况是,我需要解决一系列承诺,然后使用结果。我已经使用Q.all([arrayOfPromise])来解决所有承诺。在这里,每个promise都在执行DB操作,因此活动DB连接的数量会超过连接池的大小,并出现错误 我已经阅读了Q库文档- 但没有找到任何解决办法 const process = () => { const arrayOfIds = [id1, id2, id3, id4 .... idn]

我不熟悉nodeJS和promises,也不熟悉使用qpromise库。我面临的情况是,我需要解决一系列承诺,然后使用结果。我已经使用Q.all([arrayOfPromise])来解决所有承诺。在这里,每个promise都在执行DB操作,因此活动DB连接的数量会超过连接池的大小,并出现错误

我已经阅读了Q库文档- 但没有找到任何解决办法

const process = () => {
    const arrayOfIds = [id1, id2, id3, id4 .... idn] 
        // getById is fetching data from DB asynchronously 
    const arrayOfPromises = arrayOfIds.map(id => getById(id))

    return Q.all([arrayOfPromises])
      .then(resultArray => {
        // utilization of result array
      })
}

有人能提出更好的方法来做同样的事情吗?提前感谢。

Q
只是一个工具,不明白他们为什么要处理特定于数据库的问题

您可以做的一件事是设计一些类似队列的机制来控制允许的并发数据库操作的总大小。要排序word,请控制
阵列的大小


我不知道问题的性质,但为什么不在一个批处理查询中获取数据,而不是像其他用户建议的那样在多个
getById

中获取数据,更好的解决方法是使用
WHERE id in(…)
类型的查询

您案例中的问题是操作的并发性。N个操作正在并行执行,这导致了问题。在最坏的情况下,它们甚至可能导致NodeJS进程意外崩溃或资源使用增加

Q
或native
Promise
没有控制执行并发性的方法。如果你一定要使用Promise.all,我建议你使用
Bluebird.map
()


当然,您必须确保
getById
返回的承诺与Bluebird兼容(不确定Q承诺,但本机承诺是)

我的意思是,在sql中,它只是一个
SELECT*WHERE id in('id1','id2',…)
,为什么一开始就要使用许多
getById
?您基本上是在尝试同步异步代码。。。可能会使用某种循环,因为您的数据库连接有限。可能会创建一个新的承诺,并在带有arrayOfPromises的递归循环函数中解决它。
const process = () => {
    const arrayOfIds = [id1, id2, id3, id4 .... idn] 

    return Bluebird.map(arrayOfIds, 
        (id) => getById(id),
        { concurrency: 5 } // Default +Inifinity
    )
      .then(resultArray => {
        // utilization of result array
      })
}