One can often hear the phrase, “modern JavaScript”. This is a fig leaf, meant to cover up a sense of shame, for JavaScript has a bit of a checkered past. It started life as a badly designed language, often delivering badly conceived features. It has a reputation for slowness, crap code, and things that make you go “wat?”
Thus, “modern” JavaScript. It’s meant to be a promise that we don’t write code like that any more. We use the class
keyword and transpile from TypeScript and write fluent APIs and use promises. Yes, a promise to use promises.
Which brings us to Dewi W, who just received some code from contractors. It has some invocations that look like this:
safetyLockValidator(inputValue, targetCode).then(function () {
// You entered the correct code.
}).catch(function (err) {
// You entered the wrong code.
})
The use of then
and catch
, in this context, tells us that they’re using a Promise, presumably to wrap up some asynchronous operation. When the operation completes successfully, the then
callback fires, and if it fails, the catch
callback fires.
But, one has to wonder… what exactly is safetyLockValidator
doing?
safetyLockValidator = function (input, target) {
return new Promise(function (resolve, reject) {
if (input === target)
return resolve()
else return reject('Wrong code');
})
};
It’s just doing an equality test. If input
equals target
, the Promise resolve()
s- completes successfully. Otherwise, it reject()
s. Well, at least it’s future-proofed against the day we switch to using an EaaS platform- “Equality as a Service”.