无法从Promise函数Node.js返回值

时间:2018-07-05 09:44:27

标签: node.js promise sequelize.js

我正在使用Nodejs的续集。我想在调用此函数createMobileUser时看到ret的值,但是我变得不确定。我该如何实现。对不起,我是Node.js的新手,但是在发布此链接之前,我已经搜索了几个链接。

exports.createMobileUser = function(Mobile,reg_list) {

var ret = -1;
    if(reg_list.length ==5 && reg_list !=undefined)
    {
        var  mobile_owner_name = reg_list[0];
        var  email = reg_list[1];
        var phone_no = reg_list[2];
        var mobile_name = reg_list[3];
        var country = reg_list[4];
        var test = Mobile.create({
            mobile_mac_address: "0",
            mobile_owner_name: mobile_owner_name,
            mobile_name: mobile_name,
            mobile_owner_phone: phone_no,
            mobile_owner_email: email,
            mobile_owner_country: country,
            is_checked : "0",
            is_occupied : "0"
        }).then((result) => {
            ret = 1;
            return ret;
            console.log("inside result");
            //console.log(result);
        }).catch(err=>{
            ret = -1;
            return ret;
            console.log("inside error");
           // console.log(err);
        });
    }
    console.log(ret);
    return ret;

};
var test =   this.createMobileUser(db.Mobiles,reg_list);
//returning undefined

1 个答案:

答案 0 :(得分:1)

您应该返回一个promise

exports.createMobileUser = function (Mobile, reg_list) {
    return new Promise((resolve, reject) => {
        if (!(reg_list.length == 5 && reg_list != undefined)) return reject(-1); //better reject with some useful Error
        resolve();

    })
        .then(() => {
            var mobile_owner_name = reg_list[0];
            var email = reg_list[1];
            var phone_no = reg_list[2];
            var mobile_name = reg_list[3];
            var country = reg_list[4];
            var test = Mobile.create({
                mobile_mac_address: "0",
                mobile_owner_name: mobile_owner_name,
                mobile_name: mobile_name,
                mobile_owner_phone: phone_no,
                mobile_owner_email: email,
                mobile_owner_country: country,
                is_checked: "0",
                is_occupied: "0"
            });
            return test;
        })
        .then((result) => {
            ret = 1;
            return ret;
            console.log("inside result");
            //console.log(result);
        })
}


var test =
    this.createMobileUser(db.Mobiles, reg_list)
        .then((value) => {
            console.log("inside result", value);
        })
        .catch((err) => {
            console.log('inside error')
        })