Strickland
Search…
Automatic Race Condition Handling
Value change race conditions are a common pitfall with async validation to introduce boilerplate. To reduce this boilerplate code, Strickland can automatically handle these race conditions.
In the race condition handling example, we saw the application code check the current value against the value that async validation was performed against to determine if the value had changed. By providing Strickland with a way to get the current value during the async validation workflow, the async result can be automatically rejected if the value has changed.
This is done by passing a function to validateAsync that retrieves the current value. With that function, validateAsync will check the value when async validation completes. If the value is unchanged, the Promise will resolve normally; if the value did change during async validation, the Promise will be rejected. The rejection will include the async result, but your application typically will not consume it.
1
const usernameValidator = [
2
required(),
3
length({minLength: 2, maxLength: 20}),
4
usernameIsAvailableTwoStage
5
];
6
7
let username = 'marty';
8
let usernameResult = validate(usernameValidator, username);
9
10
username = 'mcfly';
11
12
if (usernameResult.validateAsync) {
13
usernameResult.validateAsync(() => username)
14
.then((asyncResult) => {
15
usernameResult = asyncResult;
16
})
17
.catch((rejectedResult) => {
18
// the asyncResult result will be rejected
19
// because the value has changed
20
});
21
}
Copied!

Async Validation Helper: validateAsync

The validateAsync function exported from Strickland supports this same feature. Instead of passing the value to be validated, pass a function that returns the current value. If the value changes during async validation, the result Promise will reject.
1
import {
2
validateAsync, required, length
3
} from 'strickland';
4
5
const usernameValidator = [
6
required(),
7
length({minLength: 2, maxLength: 20}),
8
usernameIsAvailableTwoStage
9
];
10
11
let username = 'marty';
12
13
validateAsync(usernameValidator, () => username)
14
.then((asyncResult) => {
15
// async validation completed
16
})
17
.catch((rejectedResult) => {
18
// async validation rejected
19
});
20
21
username = 'mcfly';
Copied!
Last modified 1yr ago