Using wait.for with nodejs and mongoskin to avoid callback hell

≡放荡痞女 提交于 2019-12-11 22:37:14

问题


I m actually developping a little application with mongodb and nodejs to create my REST Api. I face a problem when I need to access an object reference :

  • I have a roadmap collection which reference a user object
  • When I want to get all the roadmaps, I have to loop on my roadmap array to lazy load my users, by the ref ID stored in the roadmap collection
  • I have a callback problem, the user is not loaded when I need it

I have found a solution using Wait.for library : https://github.com/luciotato/waitfor , but I dont know how it works. I tried everything, but no way to make it work

all: (req,res)->
    @em.collection(@collection).find().toArray((err, result)=>
      roadmaps = []
      for r in result
        r.user = @getUser(r.user.oid)
        roadmaps.push r
      res.send(roadmaps))



 getUser: (oid)->
    @em.collection('user').findOne {_id: new @objectId(oid)}, (err, res)=>
      if !err
        return res
      return undefined

Does anybody have an idea of how to make it works properly ? Where should I put the wait.lauchFiber ? where should I put the wait.for ?

Thanks for all


回答1:


I'm not familiar with CoffeeScript, please correct me and I'll edit this answer.

all: (req,res)->
    var result = wait.forMethod(@em.collection(@collection).find(), "toArray")
    roadmaps = []
    for r in result
        r.user = @getUser(r.user.oid)
        roadmaps.push r
    res.send(roadmaps)



 getUser: (oid)->
    try
      return wait.forMethod(@em.collection('user'),"findOne",{_id:new @objectId(oid)})
    catch(err)
      return undefined

As you can see, for "getUser", if the method is that simple, you better use your version, with the callback.

"where to put the launchFiber()?"

you put the launchFiber when a request arrives. see https://github.com/luciotato/waitfor#proper-use



来源:https://stackoverflow.com/questions/25442470/using-wait-for-with-nodejs-and-mongoskin-to-avoid-callback-hell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!