如果所有字段均有效,如何返回resolve()否则返回拒绝?
let validateData = (data) => {
let fields = [
'Field1',
'Field2',
'Field3'
];
return new Promise((resolve, reject) => {
fields.forEach(field => {
if (data.hasOwnProperty(field)) {
// resolve if all matched
} else {
//reject?
}
});
});
}
主要它将具有
try {
await validateData(data);
} catch(err) {
throw new Error(`${err}`);
}
答案 0 :(得分:6)
如果数据对象上不存在任何字段,则在找到后立即拒绝。如果没有,您最终可以解决。
let validateData = (data) => {
let fields = [
'Field1',
'Field2',
'Field3'
];
return new Promise((resolve, reject) => {
fields.forEach(field => {
if (!data.hasOwnProperty(field)) {
reject();
}
});
resolve();
});
}
答案 1 :(得分:2)
NavigationPageRenderer
如果其中任何一个属性无效,只需return new Promise((resolve, reject) => {
fields.forEach(field => {
if (!data.hasOwnProperty(field)) {
reject();
return;
}
});
resolve();
});
,否则,如果所有这些属性均有效,则不会将其放入if语句中,它将解决承诺。
答案 2 :(得分:1)
错误对象将包含验证错误的描述:
let validateData = (data) => {
let fields = [
'Field1',
'Field2',
'Field3'
];
return new Promise((resolve, reject) => {
let errors = [];
fields.forEach(field => {
if (!data.hasOwnProperty(field)) {
errors.push(`ValidationFieldError: ${field}`);
}
});
errors.length ? reject(new Error(errors.join('\n'))) : resolve();
});
}
答案 3 :(得分:0)
如果所有验证有效的字段都需要异步操作,则可以使用Promise.all,只有在所有验证有效的字段都得到解决后,才能解决该问题。
例如
let validateData = async (data) => {
let fields = [
'Field1',
'Field2',
'Field3'
];
let fieldsValidatedPromsises = [];
fields.forEach(field => {
let validationPromise = new Promise( function (resolve, reject) {
if (data.hasOwnProperty(field)) {
// resolve if all matched
} else {
//reject?
}
});
fieldsValidatedPromsises.push(validationPromise);
});
return Promise.all(fieldsValidatedPromsises).then(function () {
return true;
})
.catch(function () {
return false;
});
}
let c = await validateData(data);
if (c) {
// All fields validation is successful
}
else {
// One of field validation fails
}
答案 4 :(得分:0)
一种优雅的方式是
let validateData = async (data) => {
let fields = [
'Field1',
'Field2',
'Field3'
];
let promises = [];
fields.forEach(field =>
promises.push(new Promise((resolve) =>
data.hasOwnProperty(field) ? resolve() : reject())
)
);
return Promise.all(promises);
}
演示
let validateData = async(data) => {
let fields = [
'Field1',
'Field2',
'Field3'
];
let promises = [];
fields.forEach(field =>
promises.push(new Promise((resolve) =>
data.hasOwnProperty(field) ? resolve() : reject()))
);
return Promise.all(promises);
}
async function foo() {
try {
await validateData({
'Field1': 1,
'Field2': 2,
'Field3': 3
});
console.log('valid here');
} catch (err) {
console.log('Invalid');
}
}
foo();
答案 5 :(得分:0)
还有另一种方法...
let validateData = (data) => {
let fields = [
'Field1',
'Field2',
'Field3'
];
return new Promise((resolve, reject) => {
fields.every(field => data.includes(field)) ? resolve() : reject();
});
}