Promise-they will always ask you

DaisyFighting
5 min readNov 22, 2020

You always heard about Promise while what is this and how to use this. It can be a very confusing concept. During the interview, they will always ask you to explain promise and how to solve some problems using promise. It is really essential to understand Promise.

  1. Definition

A promise is an object that may produce a single value some time in the future. The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It allows you to associate handlers with an asynchronous action’s eventual success value or failure reason.

“Producing code”: code that can take some time

“Consuming code”: code that must wait for the result

A Promise is a JavaScript object that links producing code and consuming code. It is just like a promise in real life. You only will know the result until the proper time in the future. It can be a success or a failure.

A promise is in one of these states:

  • pending: initial state, neither fulfilled nor rejected
  • fulfilled: the operation was completed successfully
  • rejected: the operation failed

2. why we use promise instead of callbacks?

If there are multiple async operations to be done and if we try to use callbacks for them, there will be a Callback hell. If we handle the same operation with Promises, the same code will be cleaner and easier to read.

// callback
firstRequest(function(response) {
secondRequest(response, function(nextResponse) {
thirdRequest(nextResponse, function(finalResponse) {
console.log('Final response: ' + finalResponse);
}, failureCallback);
}, failureCallback);
}, failureCallback);
//promise
firstRequest()
.then(function(response) {
return secondRequest(response);
}).then(function(nextResponse) {
return thirdRequest(nextResponse);
}).then(function(finalResponse) {
console.log('Final response: ' + finalResponse);
}).catch(failureCallback);

3. Promise Methods & Promise Chaining

  • How to create and use A Promise

(1) use a constructor to create a Promise object

const myPromise = new Promise();

(2)takes two parameters

const myPromise = new Promise((resolve, reject) => {  
// condition
});

(3)if the condition is met, the Promise will be resolved otherwise it will be rejected

const myPromise = new Promise((resolve, reject) => {  
let condition;

if(condition is met) {
resolve('Promise is resolved successfully.');
} else {
reject('Promise is rejected');
}
});
  • Promise methods

You must use a Promise method to handle promises.

Instance methods

Promise.prototype.then(): takes two arguments, a callback for success and another for failure; both are optional

the then() method is called after the Promise is resolved. Then we can decide what to do with the resolved Promise.

If the promise gets rejected. it will jump to the catch() method and this time we will see a different message on the console.

myPromise.then((message) => { 
console.log(message);
}).catch((message) => {
console.log(message);
});

Static methods

Promise.all(): wait for all promises to be resolved or for any to be rejected

The axios.get() method will return a promise.

The Promise.all() requires an array of promises. For example:

Promise.all([promise1, promise2, promise3]);let URL1 = "https://www.something.com"
let URL2 = "https://www.something1.com"
let URL3 = "https://www.something2.com"

const promise1 = axios.get(URL1);
const promise2 = axios.get(URL2);
const promise3 = axios.get(URL3);

Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});

An example with result:

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});
// expected output: Array [3, 42, "foo"]

Chained Promises

The methods promise.then(), promise.catch(), and promise.finally() are used to associate further action with a promise that becomes settled. These methods also return a newly generated promise object, which can optionally be used for chaining. Chaining will result in a sequence that runs in serial.

Promises are Asynchronous

Here is an example: https://jsbin.com/vepateq/edit?js,console

4. Async/Await

There is a special syntax to work with promises in a more comfortable fashion, called “async/await”. These features basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterward.

First of all, we have the async keyword, which you put in front of a function declaration to turn it into an async function. An async function is a function that knows how to expect the possibility of the await keyword being used to invoke asynchronous code.

The real advantage of async functions becomes apparent when you combine it with the await keyword — in fact, await only works inside async functions. This can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value. In the meantime, other code that may be waiting for a chance to execute gets to do so. You can use await when calling any function that returns a Promise, including web API functions.

A simple fetch.

fetch('coffee.jpg')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
return response.blob();
}
})
.then(myBlob => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});

Convert this to use async/await.

async function myFetch() {
let response = await fetch('coffee.jpg');

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
let myBlob = await response.blob();

let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
}
}

myFetch()
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});

References

--

--