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: '[email protected]' })
.then(() => console.log("All done."));
添加回答
舉報