JAVASCRIPT

Understanding Promises in JavaScript

Deep-dive into the world of JavaScript Promises

const promiseToReader = new Promise((resolve, reject) => {

setTimeout(function() {
if (userLikedTheArticle) {
resolve('This article is awesome!')
} else {
reject('I should have never been here! ;p')
}
}, enoughToReadArticle)

})

What is a Promise?

How do we create Promises?

/**
* Creates a new Promise.
*
@param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
const welcomeToPromises = new Promise((resolve, reject) => {
// This is the body if the asynchronous operation
// When this operation finishes we can call resolve(...) to set the Promise as fulfilled
// In case of failure, we can call reject(...) to set the Promise as rejected

// Let's do now something async, like waiting for a second
// Though in reallity you would probably do a remote operation, like XHR or an HTML5 API.
setTimeout(() => {
resolve('Sucess!') // Super! all went well!
}, 1000)
}

Consuming Promises, then and catch

/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
*
@param onfulfilled The callback to execute when the Promise is resolved.
*
@param onrejected The callback to execute when the Promise is rejected.
*
@returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;


/**
* Attaches a callback for only the rejection of the Promise.
*
@param onrejected The callback to execute when the Promise is rejected.
*
@returns A Promise for the completion of the callback.
*/
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
promiseToReader.then(result => {
console.log('result', result)
}, error => {
console.error('error in then', error)
})

promiseToReader.catch(error => {
console.error('error', error)
})
console.log('Initiating test...')
console.log('Good reader started reading...')
test(true)
console.log('Probably what is a bot started reading...')
test(false)
console.log('Both users are now reading, and soon I should get my results')
Initiating test...
Good reader started reading...
Probably what is a bot started reading...
Both users are now reading, and soon I should get my results
result This article is awesome!
error in then I should have never been here! ;p
error I should have never been here! ;p

Promise Chaining

fetch(url)
.then(validate)
.then(process)
.catch(handleErrors)

Avoid code duplication with Finally

finally?<U>(onFinally?: () => U | Promise<U>): Promise<U>;
promiseToReader.finally(function() {
// settled (fulfilled or rejected)
console.log("Finally settled!")
});

How do I cancel a Promise?

Extras

Async / Await

function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}

async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: 'resolved'
}

asyncCall();
> "calling"
> "resolved"

Conclusion

I’m an entrepreneur, developer, author, speaker, and doer of things. I write about JavaScript, Python, AI, and programming in general.

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