1 回答
TA贡献1785条经验 获得超8个赞
如果您从回调内部返回一个非承诺值.then,那么它将自动包装在一个承诺中。这甚至适用于默认返回值undefined.
这意味着您可以使用 if 语句有条件地创建用户。
function logIn({ shouldCreateUser, username, emailAddress }) {
console.log("In logIn...");
return Promise.resolve()
.then(() => {
console.log("In first then...");
if (shouldCreateUser) {
return createUser(username); // !
}
// If control moves here, a promise is implicitly returned with a value of `undefined`
})
.then(() => {
console.log("In second then...");
return client.sendEmail(emailAddress); // send email to everyone
})
.then(() => {
console.log("Continuing with application logic...");
})
.catch((err) => {
console.error(err.message);
//catch any unhandled promise exceptions
});
}
function createUser(username) {
console.log("In createUser...");
return client
.insertUser(username)
.then((result) => {
if (!result || !result.user || !result.isPersonaUpdated)
throw new Error("User insertion failed");
console.log("User created asynchronously ok...");
})
.catch((err) => {
console.error("Error thrown in createUser...", err.message);
});
}
const client = {
insertUser() {
return Promise.resolve().then(() => ({ user: {}, isPersonaUpdated: true }));
},
sendEmail() {
console.log("Sending email...");
return Promise.resolve().then(() =>
console.log("Email sent asynchronously ok...")
);
}
};
// Try flipping the value of `shouldCreateUser`
logIn({ shouldCreateUser: true,
username: 'Fred Bloggs',
emailAddress: 'example@example.com' })
.then(() => console.log("All done."));
添加回答
举报