gpt4 book ai didi

node.js - promise 待定

转载 作者:搜寻专家 更新时间:2023-10-31 22:24:37 26 4
gpt4 key购买 nike

我的 nodejs 应用程序中有一个类,代码如下:

var mongoose    = require('mongoose');
var Roles = mongoose.model('roles');
var Promise = require("bluebird");

module.exports = Role;

var err = null;
var id;

function Role(name, companyId) {
this.err = err;
this.name = name;
this.companyId = companyId;
this.id = getId(name, companyId);
}



var getId = function (name, companyId) {
return new Promise(function(resolve, reject) {
Roles.findOne({companyId:companyId, name:name}, function(err,result) {
resolve(result._id);
});
});
};

当我调用类时,id 是挂起的:

var currentRole = new Role(myRole, comId);
console.log(currentRole);

如何在解析后从类中获取值?

最佳答案

currentRole.id 是一个 promise ,因此您可以对其调用 then() 以等待它被解析:

var currentRole = new Role(myRole, comId);
currentRole.id.then(function (result) {

// do something with result
});

虽然这感觉像是一个奇怪的 API,但您希望您的对象在其构造函数返回时“准备好使用”。让 getId 成为 Role 原型(prototype)上的 promise 返回函数可能会更好,因此您可以执行以下操作:

var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {

// do something with result
});

您还应该考虑处理该错误以拒绝 promise :

var getId = function (name, companyId) {
return new Promise(function(resolve, reject) {
Roles.findOne({companyId:companyId, name:name}, function(err,result) {

if (err) {
return reject(err);
}
resolve(result._id);
});
});
};

并在您对 getId 的调用中添加一个拒绝处理程序:

var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {

// do something with result
}, function (err) {

// do something with err
});

或等同于:

var currentRole = new Role(myRole, comId);
currentRole.getId().then(function (result) {

// do something with result
}).catch(function (err) {

// do something with err
});

关于node.js - promise 待定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36822087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com