如果依赖于之前的Promise调用的结果,我如何维护一个平坦的Promise链:
const authorize = function ({ user, allowAdmin, allowUser }) {
return new Promise((resolve, reject) => {
if (user.username === 'admin' && allowAdmin) {
return resolve();
}
if (user.username === 'user' && !allowUser) {
return reject(new Error('Unauthorized'));
}
});
};
const parse = function (value) {
return new Promise((resolve, reject) => {
if (value < 10) {
return resolve(value * 2)
}
else {
return reject(new Error('Parser error'));
}
});
};
const validate = function (parsedValue) {
return new Promise((resolve, reject) => {
const validationErrors = [];
if (parsedValue > 16) {
return reject(new Error('Validation error'));
} else if (parsedValue > 8) {
validationErrors.push({ result: 'value must be < 8' });
return resolve(validationErrors);
}
else {
return resolve(validationErrors);
}
});
};
const execute = function (validatedValue) {
return new Promise((resolve, reject) => {
if (validatedValue < 6) {
return resolve(validatedValue)
}
else {
return reject(new Error('Execution error'));
}
});
};
const handle = function (user, value) {
authorize({ user, allowAdmin: true })
.then(parse(value))
.then(validate) // how to pass result of parse here without nesting?
.then(execute) // how to pass result of validate without nesting?
.then(console.log('done'))
.catch(error => console.log(error.message));
};
handle({ username: 'admin'}, 9);