使用wait.for与nodejs和mongoskin避免回调地狱 [英] Using wait.for with nodejs and mongoskin to avoid callback hell
问题描述
我实际上使用mongodb和nodejs开发一个小应用程序来创建我的REST Api。
当我需要访问对象引用时,我遇到一个问题:
- 我有一个路线图集合引用一个用户对象
- 当我想得到所有的路线图,我必须循环我的路线图数组懒加载我的用户,通过存储在路线图集合中的参考ID
- 我有一个回调问题,当我需要时,用户没有加载
我找到一个解决方案使用Wait.for图书馆: https://github.com/luciotato/waitfor ,但我不知道它是如何工作的。我尝试了一切,但没有办法让它工作
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
有想法如何使它正常工作?我应该把wait.lauchFiber放在哪里?
感谢所有
p>我不熟悉CoffeeScript,请更正我,我将编辑此答案。
all:(req,res) - >
var result = wait.forMethod(@ em.collection(@collection).find(),toArray)
roadmaps = []
for 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
正如你所看到的,对于getUser,如果方法很简单,
在哪里放置launchFiber()?
当请求到达时放置launchFiber。请参阅 https://github.com/luciotato/waitfor#proper-use
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
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
这篇关于使用wait.for与nodejs和mongoskin避免回调地狱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!