Which JavaScript operation waits for the process to execute till an input or output operation is completed
Answers
Explanation:
Asynchronous functions are a good and bad thing in JavaScript. The good side is that asynchronous functions are non-blocking and, therefore, are fast – especially in a Node.js context. The downside is that dealing with asynchronous functions can be cumbersome, as you sometimes have to wait for one function to complete in order to get its “callback” before proceeding to the next execution. There are a handful of ways to play to the strengths of asynchronous function calls and properly handle their execution, but one is far superior to the rest (Spoiler: it’s Async/Await). In this quick read, you’ll learn about the ins and outs of Promises and the use of Async/Await, as well as our opinion on how the two compare. Enjoy!
Promises vs. Callbacks
As a JavaScript or Node.js developer, properly understanding the difference between Promises and Callbacks and how they work together, is crucial. There are small but important differences between the two. At the core of every Promise, there is a callback resolving some kind of data (or error) that bubbles up to the Promise being invoked. The callback handler:
function done(err) {
if (err) {
console.log(err);
return;
}
console.log('Passwords match!');
}
view rawdone.js hosted with ❤ by GitHub
Calling the validatePassword() function:
function validatePassword(password) {
if (password !== 'bambi') {
return done('Password mismatch!');
}
return done(null);
}
view rawcallback.js hosted with ❤ by GitHub
The code snippet below shows a full end to end check for validating a password (it’s static and must match “bambi”, my favorite cartoon character as a child):
// provided a string (password)
function validatePassword(password) {
// create promise with resolve and reject as params
return new Promise((resolve, reject) => {
// validate that password matches bambi (the deer)
if (password !== 'bambi') {
// password doesn't match, return an error with reject
return reject('Invalid Password!');
}
// password matches, return a success state with resolve
resolve();
});
}
function done(err) {
// if an err was passed, console out a message
if (err) {
console.log(err);
return; // stop execution
}
// console out a valid state
console.log('Password is valid!');
}
// dummy password
const password = 'foo';
// using a promise, call the validate password function
validatePassword(password)
.then(() => {
// it was successful
done(null);
})
.catch(err => {
// an error occurred, call the done function and pass the err message
done(err);
});
view rawvalidate-password.js hosted with ❤ by GitHub
The code is commented pretty well, however, if you’re confused, the catch only executes in the event that a reject() is called from the promise. Since the passwords don’t match, we call reject(), therefore “catching” the error and sending it to the done() function.
mark me as bainlist