我目前有两个诺言,而孩子则取决于父母的成功。我想从孩子的诺言中“解决” /拒绝父母的诺言。
const UserApplicaiton = require('../applications/user'), User = new UserApplicaiton();
class CheckParams {
constructor() { }
required(params, required_params) {
return new Promise(function(resolve, reject, onCancel) {
// set i
var i;
// set missed_required_params
var missed_required_params = [];
// check for userCredentials if user_id is required param, convert from credentials to user_id
if(required_params.includes("user_id")){
// set as const
const user_key = String(params.userCredentials.user_key);
const user_secret = String(params.userCredentials.user_secret);
// check in database
User.info(user_key, user_secret).then((data) => {
// if data
if(data) {
// add user_id to params
params.user_id = data[0]._id;
// loop params
for(i = 0; i < required_params.length; i++){
// if params that's required is there, else add to array
if(!(required_params[i] in params)){
missed_required_params.push(required_params[i]);
}
}
if(missed_required_params.length !== 0){
reject("Missed parameters: " + missed_required_params);
}else{
resolve(params);
}
}
}).catch((err) => {
reject(err);
});
}else{
// loop params
for(i = 0; i < required_params.length; i++){
// if params that's required is there, else add to array
if(!(required_params[i] in params)){
missed_required_params.push(required_params[i]);
}
}
if(missed_required_params.length !== 0){
console.log("hello");
return reject("Missed parameters: " + missed_required_params);
}else{
console.log("hello2");
resolve(1);
}
}
});
}
}
module.exports = CheckParams;
第二个Promise的目标是根据响应将其添加到对象中,然后解析父Promise,这将在以后的代码中使用。
这根本不起作用。异步并没有真正的帮助。
答案 0 :(得分:1)
您的问题似乎是if(data) {
缺少else
子句,您也将在其中履行承诺。避免使用Promise
constructor antipattern也有助于避免此类错误。
required(params, required_params) {
var promise;
if (required_params.includes("user_id")) {
const user_key = String(params.userCredentials.user_key);
const user_secret = String(params.userCredentials.user_secret);
promise = User.info(user_key, user_secret).then((data) => {
if (data) {
params.user_id = data[0]._id;
}
// else
// throw error? keep user_id undefined?
})
} else {
promise = Promise.resolve();
}
return promise.then(() => {
var missed_required_params = [];
for (var i = 0; i < required_params.length; i++) {
if (!(required_params[i] in params)) {
missed_required_params.push(required_params[i]);
}
}
if (missed_required_params.length !== 0) {
throw new Error("Missed parameters: " + missed_required_params);
} else {
return params;
}
});
}