Callbacks Vs Promises and basics of JS

1. What is (req,res) => {} notation in JS ?

2. What does bind method do in JS ?

var Button = function(content) { 
this.content = content;
};
Button.prototype.click = function() {
console.log(this.content + ' clicked');
}

var myButton = new Button('OK');
myButton.click();

var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the global object

var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
OK clicked
undefined clicked
OK clicked

3. What is Closure?

function multiplier(a) {
return function (b) {
return a * b;
}
}
let multiplyByTwo = multiplier(2);
console.log(multiplyByTwo(10))
// Prints 20
// *** Lets use ES6 for the above task *** //let multiplier = (a) => {
return (b) => {
return a * b;
}
}
let multiplyByTwo = multiplier(2);
console.log(multiplyByTwo(10))
// Prints 20

4. What is yarn?

  • installing packages wasn’t fast/consistent enough, and
  • there were security concerns, as npm allows packages to run code on installation.

Callbacks or Higher Order Functions

function myFetchData(url, callback) { 
makeNetworkCall( url, (response) => {
if (response.success) {
callback(response.data, nil)
} else {
callback(nil, response.error)
}
});
}
/* Imagine makeNetworkCall makes a get call to the url which it accepts as the first param. On executing the call, it fills its response in the second argument it takes */
let url = "https://jsonplaceholder.typicode.com/todos/1";myFetchData(url, function(data, error) {
if (error != nil) {
console.log("data", data)
} else {
console.log("error", error)
}
});

Promises

How Promise work
// Here's how you create a promise:var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…

if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
get('supplyData.json').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.log("Failed!", error);
})
get('supplyData.json').then(function(response) {
console.log("Success!", response);
}).catch(function(error) {
console.log("Failed!", error);
})
get('supplyData.json').then(function(response) {
console.log("Success!", response);
}).then(undefined, function(error) {
console.log("Failed!", error);
})
let myFetchData = (url) => {
return new Promise((resolve, reject) => {
makeNetworkCall( url , (response) => {
if (response.success) {
resolve(response.data)
} else {
reject(response.error)
}
});
})
}
/* Imagine makeNetworkCall makes a get call to the url which it accepts as the first param. On executing the call, it fills its response in the second argument it takes */
let url = "https://jsonplaceholder.typicode.com/todos/1";myFetchData(url)
.then(data) {
console.log("data", data)
}
.catch(error) {
console.log("error", error)
}
getJSON('supplyData.json').then(function(supply) {
return supply[0];
}).then(function(supply0) {
console.log("Got supply0!", supply0);
})
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000); // (Zone 1)
})
.then(function(result) { // (Zone 2)
alert(result); // 1
return result * 2;
})
.then(function(result) { // (Zone 3)
alert(result); // 2
return result * 2;
})
.then(function(result) {
alert(result); // 4
return result * 2;
});
fetch('/article/promise-chaining/user.json')
.then(response => response.json())
.then(user => fetch(`https://api.github.com/users/${user.name}`))
.then(response => response.json())
.then(githubUser => new Promise(function(resolve, reject) {
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);

setTimeout(() => {
img.remove();
resolve(githubUser);
}, 3000);
}))
// triggers after 3 seconds
.then(githubUser => alert(`Finished showing ${githubUser.name}`));
Promise.all(arrayOfPromises).then(function(arrayOfResults) {
//...
})

Difference between callback and promises

Async & Await

--

--

--

Buliding influencerbit.com | Guitarist | Traveller | Entrepreneur

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Web Applications: Analyzing Client-Side Performance

Everything You Need to Know About Regular Expressions in JavaScript

Alexa Custom Skill Development

Puppeteer Extensions: Automate Logins with Google, Block Ads, and Add Anonymity

How To Make Redux Seamless

Building macOS clone in Angular

boot screen angular

Create a Pomodoro Timer using JavaScript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhinav Rai

Abhinav Rai

Buliding influencerbit.com | Guitarist | Traveller | Entrepreneur

More from Medium

Collaborative Drawing App: Introduction

Image Compression is Everything

Version Controlling | NoSql

How to install Node.js and npm using Node Version Manager (NVM)