javascript - Node.js 第一次使用 promise 不更改数据

标签 javascript node.js express promise

<分区>

我的代码有这个问题,我有一种数据,我需要在用户请求时获取最新数据,我使用 promise 来获取正确的数据,这部分工作正常。

我的下一个问题是我第一次请求数据时,它什么也没有返回,但是,如果我单击 agin 获取数据,它会返回正确的数据,所以这里出了点问题。

我的 promise 函数

var insert = new Promise(function(fulfill) {
  fulfill('test');
});

我的导出模块

exports.signup = function(db, user_conf) {
    var self = this;

    defineUser(user_conf);
    insert.then(function(result) {
        self.json_response = result;
      console.log(result);
    }).catch(function(e) {
      console.log(e);
    });

    return self.json_response;
}

我的快速路线功能

router.post('/signup', function(req, res, next) {

    var post = req.body;

    json_response = users.signup(req.db, {
        'fullname' : post["account-fullname"],
        'username' : post["account-username"],
        'email' : post["account-email"],
        'password' : post["account-password"],
        'retype-password' : post["account-retype-password"],
        'accept-terms' : post["accept-terms"]
    });

    res.send(json_response);
});

我需要的是我需要我的注册部分的响应以了解可以创建用户,或者在创建用户之前用户需要知道某种验证错误。

最佳答案

脱离我的头脑 - 尝试这样的事情

exports.signup = function(db, user_conf) {
    defineUser(user_conf); // I'm assuming this is synchronous
    return insert.then(function(result) {
        // do something here maybe? if not then you only need to return insert;
        return result; // return a result
    });
}

// if nothing is being done in the then callback above, this can be simplified to

exports.signup = function(db, user_conf) {
    defineUser(user_conf); // I'm assuming this is synchronous
    return insert;
}

router.post('/signup', function(req, res, next) {
    var post = req.body;
    users.signup(req.db, {
        'fullname' : post["account-fullname"],
        'username' : post["account-username"],
        'email' : post["account-email"],
        'password' : post["account-password"],
        'retype-password' : post["account-retype-password"],
        'accept-terms' : post["accept-terms"]
    }).then(function(json_response) {
        res.send(json_response);
    });
});

关于javascript - Node.js 第一次使用 promise 不更改数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33720745/

相关文章:

javascript - Mongoose 预保存使用不正确的 "this"上下文?

node.js - 发送后无法设置标题。使用 Node 和 express 第二次调用 REST API

javascript - URL 中带有动态参数的快速路由

javascript - 如何减去对象值

javascript - 隐藏所有内容后如何显示某些元素?切换不起作用

javascript - 将字符串注入(inject)到从 Node.JS 应用程序中的服务器端环境变量在客户端执行的 Javascript 文件中?

javascript - 使用正则表达式捕获冒号和逗号之间的字符

node.js - 使用 net nodejs 模块单击按钮连接到套接字服务器

angularjs - 使用 multipartFile 上传图像的注册表单

node.js - 无法从带有 SSL 的域通过 POST 来表达服务器