javascript - Node.js Express 和 Mongoose,在 save() 之后渲染

标签 javascript node.js asynchronous express mongoose

我刚刚开始尝试使用 Node.js Express 和 Mongoose 创建一个简单的博客网站。

我正在尝试构建一些路由来执行一些简单的数据库操作,但我对异步函数以及我的代码是否每次都会正确执行感到困惑。

这基本上就是我所拥有的:

app.get('/createUser', function(req, resp) {
    var newUser = new User({name: 'abc123', pass: 'password321'});
    newUser.save(function(err){ // will this callback always be called correctly?
        if(err) resp.send('ERROR!');
        resp.send('SUCCESS!');
    });
});

所以我希望将响应写为“错误!”如果保存时出现任何错误,则显示“成功!”当保存成功时。但是,我对这些功能的时间安排感到困惑。 get() 函数会在 save() 完成之前返回吗?如果是的话,回复会不会写不正确?

最佳答案

get() 函数将在 save 函数执行之前完成,但由于在执行 save 回调之前没有任何内容写入响应,因此在此之前浏览器将无法使用响应.

我在您的代码中添加了一些 console.log() 调用,以便您可以看到执行顺序:

app.get('/createUser', function(req, resp) {

    console.log('this will print first');

    var newUser = new User({name: 'abc123', pass: 'password321'});
    newUser.save(function(err){ // will this callback always be called correctly?

        console.log('this will print last');

        if(err) {
            resp.send('ERROR!');
        }
        else {
            resp.send('SUCCESS!');
        }
    });

    console.log('this will print second');

});

关于javascript - Node.js Express 和 Mongoose,在 save() 之后渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13829071/

相关文章:

javascript - Protractor ,迭代元素: Failed: stale element reference

javascript - 向 Azure Blob 存储 [REST API][Azure Blob 存储] 发出 GET 请求时授权失败

javascript - Angular 5 : adding types to external JS file

javascript - 在javascript中同时触发/触发多个函数时如何设置函数执行顺序?

node.js - 我应该如何在 mongodb/nosql 中存储数据?

javascript - Javascript 回调的处理方式有何不同?

python - 最大化并行请求数 (aiohttp)

javascript - 这个 Oauth 请求中我的 JSON 有什么问题?

node.js - Express 3.4.8 图片上传问题 - 不使用bodyParser()如何解决?

javascript - Node.js promise 有时不会执行