gpt4 book ai didi

javascript - 如何从 Sails.js 中的此方法返回 n 的值

转载 作者:行者123 更新时间:2023-12-01 03:37:56 24 4
gpt4 key购买 nike

getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;

User
.count({
where: whereConditions,
})
.exec((err, n) => {
console.log(n);
return n;
});
}

上面的方法在调用时返回undefined,但是当我console.log n时,我得到了正确的输出。我该如何解决这个问题?

最佳答案

where()应该返回 promise这意味着您可以使用 then()catch()在代码中调用getCount(filter)您的“服务”,以根据需要访问值和错误的成功响应。根据documentation , .exec()可以直接替换为then()catch() 。尝试如下操作:

服务:

getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;

// return promise
// using this value directly will not allow you to access queried values
return User.count({ where: whereConditions });
}

Controller /调用者:

this.someService.getCount('someFilterValue')
.then(values = {
console.log(values);
// do something with values like bind to variable/property of the view
})
.catch(error => console.log(error));

或者根据您的结构,您可以尝试类似的方法来完成 getCount() 内的所有操作:

getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;

// return promise
// using this value directly will not allow you to access queried values
return User
.count({ where: whereConditions })
.then(values => res.json(values))
.catch(error => res.serverError(error));
}

您可以委托(delegate) then() 中的功能的getCount()到一个单独的方法来减少重复:

 getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;

// return promise
// using this value directly will not allow you to access queried values
return User
.count({ where: whereConditions })
.then(handleResponse)
.catch(error => res.serverError(error));
},

handleResponse: (data) => {
// do something with data
return data.map(e => e.someProperty.toUpperCase());
}

您可以链接then()每次返回转换后的值时,根据需要继续转换值。只要继续返回值,您就可以将其委托(delegate)给方法。这还允许您采取异步操作,并且仅在解决它们后才对其进行操作。

getCount: (filter = null) => {
var whereConditions = {};
if(filter != null) whereConditions.role = filter;

// return promise
// using this value directly will not allow you to access queried values
return User
.count({ where: whereConditions })
.then(values => values.map(e => e.someProperty.toUpperCase()))
.then(transformedValues => transformedValues.filter(e => e.indexOf(filter) > -1))
.then(filteredValues => res.json(filteredValues))
.catch(error => res.serverError(error));
}

希望有帮助!

关于javascript - 如何从 Sails.js 中的此方法返回 n 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44114808/

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