2017-04-24 143 views
0

我在猜测我正在做这个错误的方式,应该使用promises或其他东西,但我试图创建一个CMS,从而您可以编辑一个mongodb文档,然后转换成博客文章或任何模板与变量填写。防止函数调用,直到在javascript/node.js中定义变量为止

我的CMS创建了一个只有博客图像,作者,标题,修改日期以及mongodb文档_id作为data-id属性的博客列表。

当您点击其中一个博客时,它通过socket.io将blogId传递给服务器,服务器搜索博客,然后呈现blogTemplateForm.pug文件,并将该html发送回客户端进行客户端检查如果#editor容器中已经有html,则删除该html,然后在编辑容器内追加新的html,然后用户可以对其进行编辑。

现在这个文档查找是由一个猫鼬模型处理的,然后我通过回调函数将res.blog设置为该查找返回的博客,我生成了一些表单供以后使用,否则我们会使用该res .blog对象来从blogTemplate生成我们想要的html,然后将该html发送给客户端。

这很好,但由于某些未知的原因,res.blog对象有时是不确定的,即使它真的不应该,也就是说。在接下来的功能..喜欢什么?所以app.render()会返回一个错误,并为null返回null,所以我做了一个循环来检查博客是否在渲染模板之前被定义。但即使这样做不起作用,因为html有时会被视为null ...什么给了?!

Failure

Success

如果你看看我的循环检查res.blog是否定义它真的是没有意义的,任何不确定res.blog对象是通过做它的方式。

socket.on('edit blog', function(blogId){ 
     var res = {}; 
     Blog.findById(blogId, function(err, blog){ 
      res.blog = blog 
      res.form = Form(blog) 
     }).then(function(){ 
      res.filledForm = Bridge(res.blog, res.form).getForm() 
      delete res.form 
      if (res.blog !== (undefined & null)) { 
       app.render(blogTemplateFormPath,{blog: res.blog}, function(err, html){ 
        console.log(err); 
        console.log(html); 
        socket.emit('blog form', html) 
       }) 
      } else while (res.blog == (undefined | null)) { 
       if (res.blog !== (undefined & null)) { 
        app.render(blogTemplateFormPath,{blog: res.blog}, function(err, html){ 
         console.log(err); 
         console.log(html); 
         socket.emit('blog form', html) 
        }) 
       } 
      } 
     }) 
    }) 

我使用不同的操作数尝试,但都无济于事,始终返回null左右的时间

if (res.blog !== (undefined | null)) { 
    app.render(blogTemplateFormPath,{blog: res.blog}, function(err, html){ 
     console.log(err); 
     console.log(html); 
     socket.emit('blog form', html) 
    }) 
} else while (res.blog == (undefined | null)) { 
    if (res.blog !== (undefined | null)) { 
     app.render(blogTemplateFormPath,{blog: res.blog}, function(err, html){ 
      console.log(err); 
      console.log(html); 
      socket.emit('blog form', html) 
     }) 
    } 
} 

感谢您的帮助5%。截图是高分辨率1080p x 2,所以我认为你将能够看到代码。

回答

0

这看起来腥:

Blog.findById(blogId, function(err, blog){ 
     res.blog = blog 
     res.form = Form(blog) 
    }).then(function(){ 
     ... 
    }); 

你传递一个回调findById()也把它当作一个承诺。我可以想象这可能会导致各种意想不到的问题。

所以只使用一种方法。我的建议是使用这个承诺:

Blog.findById(blogId).then(function(blog) { 
    if (! blog) { 
    ...handle "blogId not found" here... 
    return; 
    } 
    ... 
}).catch(function(err) { 
    ...handle errors here... 
}); 

这也将消除对res的需求。

+0

谢谢,完美的作品,是的,这是一些不好的代码,我的坏。我的朋友对你很爱和幸运<3 – lopu

0

因为res.blog !== (undefined | null)没有做你认为它正在做的事情。

console.log((undefined | null)) // 0 

没有捷径,你需要检查每一个。

if (res.blog !== undefined && res.blog !== null) 

或做虚假支票

if (!res.blog)