0

My co-worker and I were having a discussing and we were trying to figure this out. Assuming I have a NodeJS application connected to Mongo I am trying to reason about how this code will work. Here is a contrived example.


    // #1 is an async request but it's not awaited and
    // the promise is saved as a variable. because its
    // an aggregate query it takes some time but i'm not
    // concerned with the result just yet. 
    const promise = Model.find(aggregateQuery);

    // #2 this a computationally heavy process
    for (let item of await Model.find(query)) {
       const result = dataManipulation(item);
       const updates = await Model.findOneAndUpdate({ _id: item._id }, result);
    }

    // #3 ok, now I'm hoping Mongo has an answer for me
    const answer = await promise();

I'm trying to reason about the behaviour of the promise. Will Mongo work on 1 and 2 using its threads? Does it matter whether or not #1 is await?

EQuimper
  • 5,811
  • 8
  • 29
  • 42
Peter
  • 4,493
  • 6
  • 41
  • 64
  • 1
    it doesn't matter what mongo does because javascript io is single threaded. If you want them to execute at their own speed then put the computationally heave code in it's own promise and use Promise.all, that way it will only take as long as the slowest operation. – I wrestled a bear once. Aug 16 '19 at 16:42
  • @Iwrestledabearonce. Thanks. I get the single threaded nature. Maybe this SO [answers **partly**](https://stackoverflow.com/questions/21957187/can-i-do-a-lazy-promise-with-bluebird-js) what I want. – Peter Aug 17 '19 at 06:02
  • I'm voting to close because I found [an answer](https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all). > Note that Promise.all() doesn't trigger the promises to start their work, creating the promise itself does. – Peter Aug 17 '19 at 06:04

0 Answers0