Uploaded image for project: 'Node Driver'
  1. Node Driver
  2. NODE-1231

Cursor.forEach should support returning a Promise

    XMLWordPrintable

    Details

      Description

      At the moment. cursor.forEach is returning undefined.
      So this code:

      var mongo = require('mongodb')
      var pms = require('util').promisify
       
      ;(async function () {
        try {
          var db = await pms(mongo.MongoClient.connect)('mongodb://localhost/whatever', {})
          var usersImages = db.collection('usersImages')
       
          var images = await usersImages.find({})
       
          var i = await images.forEach(image => {
            console.log(image.image)
          })
          console.log("RETURNED:", i)
       
          console.log('END OF CYCLE')
        } catch (e) {
          console.error('Error:', e)
        }
      })()
      

      Doesn't work as expected, as RETURNED will be undefined and "END OF CYCLE" will display right away, before the resultset is returned.

      This works:

      var mongo = require('mongodb')
      var pms = require('util').promisify
       
      ;(async function () {
        try {
          var db = await pms(mongo.MongoClient.connect)('mongodb://localhost/whatever', {})
          var usersImages = db.collection('usersImages')
       
          var images = await usersImages.find({})
       
          images.forEachPms = pms(images.forEach)
       
          var i = await images.forEachPms(image => {
            console.log(image.image)
          })
          console.log("RETURNED:", i)
       
          console.log('END OF CYCLE')
        } catch (e) {
          console.error('Error:', e)
        }
      })()
      

      Here I basically promisify manually the forEach call.

        Attachments

          Activity

            People

            • Votes:
              0 Vote for this issue
              Watchers:
              2 Start watching this issue

              Dates

              • Created:
                Updated:
                Resolved: