简体   繁体   English

使用 Promise.all() 并行更新 Firestore 文档

[英]Updating Firestore Documents in Parallel Using Promise.all()

This question concerns the Firestore database, but, more generally, it concerns making async requests in parallel .这个问题涉及 Firestore 数据库,但更一般地说,它涉及并行发出异步请求

Simply put, I wish to update multiple Firestore documents as quickly and efficiently as possible by mapping over an array of their document IDs.简而言之,我希望通过映射一组文档 ID 来尽可能快速有效地更新多个 Firestore 文档。

the .set() method is async (returning a promise) and so I understand that I can wrap the multiple requests - ie the map() - in a Promise.all() function, which will return a single promise once all of the requests have resolved. .set()方法是异步的(返回一个承诺),所以我知道我可以将多个请求 - 即map() - 包装在Promise.all() function 中,这将返回单个 ZB321DE3BDCD7D99EC80请求已解决。

However, it is not at all clear to me whether I should await the set() within the map() .但是,我完全不清楚我是否应该map()等待set() ) 。

Whichever way I write the code (ie with or without await), it does not appear to make a difference to speed, but does it, or should it?无论我以哪种方式编写代码(即有或没有等待),它似乎都不会对速度产生影响,但确实如此,还是应该如此?

What is the correct way to achieve the greatest speed and efficiency in this instance?在这种情况下,实现最大速度和效率的正确方法是什么?

    const update_promises = array_of_ids.map(async id => {

      const new_values = {
        new_values_1: "val1",        
        last_update: new Date()
      }      

      return await db.collection("my_collection").doc(id).set(new_values, { merge: true });

      // OR SHOULD IT BE:

      // return db.collection("my_collection").doc(id).set(new_values, { merge: true });
    })

    return await Promise.all(update_promises)

When get call set(), the SDK is going to immediately pipeline the write request over the a single managed connection.当调用 set() 时,SDK 将立即通过单个托管连接管道写入请求。 If you want to write a bunch of documents as fast as possible, you should kick them all off, then await the results at the end.如果你想尽可能快地写一堆文件,你应该把它们全部踢掉,然后等待最后的结果。 You probably don't want to await each one individually, since you are causing the code to stop for a moment while it waits for the result before the next one can get sent.您可能不想单独等待每个,因为您会导致代码在等待结果之前停止片刻,然后才能发送下一个。 That said, the performance impact is probably negligible overall, unless you have a lot of work to be done in between each write.也就是说,总体而言,性能影响可能可以忽略不计,除非您在每次写入之间有很多工作要做。

My general rule is to only await an individual promise if its result is needed right away before moving on.我的一般规则是仅等待单个 promise 如果在继续之前立即需要其结果。 Otherwise, collect all the promises together into an array for a single await with Promise.all() .否则,使用Promise.all()将所有承诺一起收集到一个数组中以进行单个等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM