23
loading...
This website collects cookies to deliver better user experience
async/await
. But sometimes incomplete understanding of this technology(as in any other) can lead to unpredictable behavior, which can confuse uses, and take hours for you to understand the cause of the problem.const handleSave = userData => {
saveUser(rawUserData)
.then(user => showNotification(`User ${getUserName(user)} has been created`))
.catch(err => showNotification(`User was not created because of error`));
};
saveUser
request, but also for the onFulfilled
block. Thus, if then
throws the error (e.g. the getUserName
function throws) then the user will be notified that user creation failed with error, even though it was.then/catch
blocks, so that the catch
is attached to the saveUser
call directly. This paves the way for another issue.const handleSave = async userData => {
try {
const user = await saveUser(userData);
showNotification(`User ${getUserName(user)} has been created`);
} catch(error) {
showNotification(`User was not created because of error`));
}
};
then
block in correct order, which feels harder to read.const handleSave = userData => {
saveUser(userData)
.then(
user => showNotifications(`User ${getUserName(user)} has been created`),
err => showNotifications(`User was not created because of error`));
);
};
then
with the two callbacks. The responsible code is less explicit and readable than dangerous code - it is temptingly dangerous to misuse the API - while feeling more explicit and readable!async/await
looks strange. Having to define variables in a higher scope feels like a bad control flow. It feels like we're working against the language:const handleSave = async userData => {
try {
const user = await saveUser(rawUserData)
.catch(() => showNotifications(`User could not be saved`))
showNotifications(`User ${displayName(user)} has been created`);
} catch(error) {
console.error(`User could not be saved`));
}
};
const createUserHandler = userData => {
saveUser(userData)
.then(sendWelcomeMessage)
.catch(sendErrorMessage)
};
const createUserHandler = userData => {
saveUser(userData)
.then(user =>
sendWelcomeMessage(user)
.catch(sendErrorMessage)
);
};
const createUserHandler = userData => {
saveUser(userData)
.catch(logUserCreationError)
.then(sendWelcomeEmail)
.catch(sendErrorMessageByEmail)
};
sendWelcomeMessage
failed, we will need to send error message for user email.then
block which calls sendWelcomeEmail
will be triggered, and because there is no user, it will throw, and we will create a email for a non-existing user.const createUserHandler = userData => {
saveUser(userData)
.then(
logIssues,
user =>
sendWelcomeEmail(user)
.catch(sendErrorMessageByEmail)
);
};