DEV Community

JavaScript Promise Guides

A JavaScript Promise is one of several ways to do asynchronous programming in JavaScript, and progress from one part of a program to the next. Get into all the details with these guides.

This is a collection of top and trending guides written by the community on subjects related to JavaScript Promise concepts. For all things JavaScript, check out the JavaScript tag! Please contribute more posts like this to help your fellow developer in need.

Javascript: How to access the return value of a Promise object

A Promise is an object representing the eventual completion or failure of an asynchronous operation.


How to rewrite a callback function in Promise form and async/await form in JavaScript

Here's the link to the code demonstrating the callback -> Promise and callback -> async/await versions.


Converting a Promise into an Observable

When working with rxjs, you might find yourself in a situation where you want to integrate a promise in a reactive code base. In order to embrace the full reactivity, it's a good idea to convert that promise into an observable so we can easily pipe other operators or even combine it with other streams.


How to use Promise in Java

I've developed a promise library for java so let me introduce it.


Elegant way to check if a Promise is pending

There's no solid way to check if a Promise is pending or finished, at least not in Node.js, so I wrote this simple snippet back in few months ago while I was searching for a simple way. I couldn't' find anything with one line max that will check the state of a promise so I came up with this simple solution. I have posted this solution on StackOverflow too. It's nothing special just an elegant & hacky way but works flawlessly on every Node.js version from 8~14. It's not stable though and the rational solution here should be a native method inside V8's core to check if a promise is pending or not.


Using a Promise in a click eventListener - more than once.

While this works perfectly, there are two big problems:

1) Promise only runs once. When it resolves with an existing ID, I can't go to the previous view and click a different element - it would have already run and still renders the first thing clicked.

2) The await part of the async/await only will work as intended when it receives a Promise. So can't just pass an ID as a string/number - returns undefined and everything breaks.


Convert A Promise To ASYNC/AWAIT

How to convert a promise-based asynchronous code to async/await format, thus making it more readable?


Returning A Promise From A Function Is Extra Useful With TypeScript

In this post, I'm going to show some examples from that project that show the utility of returning promise options from JavaScript functions and how much more useful it is with TypeScript.


Handling async operations and promise values in javascript arrays

Now let us treat findById as an async function and fix our code to ensure our promise is resolved before running any operations that depend on our resolved data.


Creating a deferred promise hook in React

Hello fellow readers! In this post I am going to show how to create and use a deferred promise hook in React. Feel free to ask or give your opinion in the comments section.

It is important that you may have some knowledge about promises to fully understand this article. If you don't, please read this great article from MDN.

Let's go!


A real-life example of making a custom Promise in JavaScript/TypeSctipt

But wait, it's 2021. Cool kids don't do that anymore. What we need, is to make our function return something awaitable. And there is nothing more awaitable than a Promise. Here is the Promise constructor


Cancelable Promise util

I found myself using this code and some derivatives time and time again so I decided to share. It's not written by me, and I found it on Edd Mann's blog. There are a few npm libraries that deal with promise cancellation in a similar manner, but I somehow prefer to have this few lines of source code somewhere in my util functions.


Resolve a Promise from outside, after return

Have you ever been at a situation where you wanted to resolve a Promise you returned from outside, when needed?


Cancelling a Promise with React.useEffect

In the code above, the fetchBananas function returns a promise. We can "cancel" the promise by having a conditional in the scope of useEffect, preventing the app from setting state after the component has unmounted.


Why is my promise not resolving correctly?

For some reason, the promise I created at usersTable.create is not resolving correctly. When I call .then() after, I get the error: UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'then' of undefined.


I Promise this is a practical guide to Async / Await

The resolveAfter2Seconds function will return a new Promise. Every promise has a state. The initial state is pending. After that, it can change to fulfilled or rejected. When it is fulfilled it will pass the value from the resolve to the then function you can then do whatever you want with it. If the state changes to rejected then it will run the catch() function. I hope the very basics of promises are now clear.


ES6 Promise | Promise.all | Promise.race | Promise.allSettled

Hey guys ! Once again I'm back with an indepth video were we discuss ES6 Promises. I know that async/await is the new way people prefer to deal with async code but I think it's always good to know about callback functions, promises, and promise methods.


Detecting a promise that will never resolve/ reject

I ran into an interesting JavaScript problem today: How to detect a promise that will never resolve/ reject?


Why to use async & await instead of the Promise class?

Promises are a way to write asynchronous code, which means that a function will return some data in a certain time in the future and the code will continue to execute. For example let's say we want to make a burger because we are hungry. So what we do, we can put the meat on the stove, and in parallel with this we can cut the vegetables. When the meat is ready we remove it from the hot plate and put it in the burger, then we put the vegetables and we are ready. Cooking the meat is the Promise and when it is ready we do something with it, this is what we call asynchronous programming.


What does Javascript Promise us for 2020?

Promises are available since ES2015 to simplify the handling of asynchronous operations. Promises have two well-known combinators: all and race. Both of them are useful, but they don't cover all the use-cases. What if we want to wait for all the Promises even if some of them go to error or only the first successful operation is essential? I'll show you the new Promise combinators that will help you give the answers to these questions.


Cancel a Promise when using XState

But that's actually not the case when using Promise-based APIs since by design they don't contain any notion of 'clean up' or 'tear down' logic.


Construindo uma Promise do zero

Promises são estruturas que lidam com valores que podem ser obtidos futuramente em uma execução, por exemplo, uma requisição para um servidor externo, ou então uma leitura de um arquivo. O que poucos sabem é que, de fato, a Promise é um padrão de projeto que pode ser implementado utilizando orientação a objetos e a especificação descrita no PromisesA+.


RxJS - Promise vs Observable

Let's first try to create a Promise and an Observable which just finishes with one value.


🚀 [GIF] Cheatsheet for Javascript Promise API methods - Promise.all, Promise.allSettled, Promise.race, Promise.any

Consider the GIFs like watching a slow-mo video of Promise API methods in action. The scenarios for each Promise API describe how they work with an emphasis on Promise status transition, value/reasons, and the order.


Javascript - Promise ou Observable

No exemplo acima conseguimos ver como ela é ansiosa, porque ao declarar a Promise o conteudo dela já é executado imediatamente, sem mesmo esperar ser invocada através do then.


Returning A Promise From A JavaScript Function Is Useful

One JavaScript feature that has tripped me up a bit recently is the difference between a function that returns a promise and a function that returns the value of that the promise resolves. Decoupling data fetching helps with server-side rendered apps and can also make mocking a remote API in tests easier. In my case, I wanted to use the same functions for getting data into a static file generator as I used in the React client.


3 most powerful JavaScript Promise methods

A Promise is an Object that is used to return a deferred computation. Mostly the deferred computation is asynchronous operation. The function that return a promise, we can attach success and failure callback. For example


The non-broken promise of static typing

A while back I read an article about how static typing does not prevent

bugs being added to software. The article is appropriately named: The broken promise of static typing. The author conducted research by generating and comparing 'bug density' scores for GitHub repositories. The bug density score was determined by getting the average number of issues labelled 'bug' per repository.


I promise this hook will blow your 1000+ lines of Async code

fetchBook fetches data from the API and results in Promise which returns book data on resolution and error on rejection.


Async/await & Promise interoperability

There are still things that are easier to do in Promise syntax. What is more, programming in async/await without understanding what is happening underneath might lead to actual inefficiencies or even errors.


Client-side global error handling and unhandled promise rejections

When dealing with Promise rejections, you will have to use a different approach. According to MDN you'll find the following window.onunhandledrejection. It states as such:


Top 10 Promise Way to Build and Level Up your Coding Skills

Once the status updated, pending->fulfilled or pending->rejected, it can be changed again. The prom1 is different from prom2 and both of them return new Promise status.


An Easy Way to Understand Promise in Javascript

According to MDN Web docs, "The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value."


Use Promise for popup

There are lot of things you can do with Promise. Today, I will share my experience on using promise for modal which I recently learned.


I Promise Your Deep Understanding of Promise

I describe background system of asynchronous function in Javascript and how to use promise a little.


Await, Promises & Promise Methods

Tl;dr finished up talking about await and execution blocking.

Went over why Promise is still valuable and powerful even if not using

.then()


📩 Use web Workers and other Windows through a simple Promise API

post-me is a typescript library that provides a simple promise-based API for bidirectional communication with web workers and other windows (iframes, popups, etc.).


await Promise !== coroutine

Someone may ask: why a Promise must be asynchronous? Can't we have a synchronous Promise? (off-topic: the executor function in Promise constructor is executed synchronously.) The answer is: it could be but it shouldn't be. Having an asynchronous model simplifies the design, as Promise represents the eventual result of an asynchronous operation. For a Promise we only concern the value (and/or reason for no value). So a Promise just tell you "I'll eventually give you a value but not sure about when it's available (and doesn't necessarily to be in a micro-task.)". Even a fulfilled/rejected Promise notifies the value asynchronously, to make the design consistent. So you know the callback in .then is always deferred. Otherwise,


Modal Dialogs as a Promise Versus Inline

This is a poor use-case for promise-based modals. Despite being presented as a modal, we're still in an actual <form> with live validation, and that validation may change which email templates we're allowed to choose or vice-versa. Keeping that validation intact when the modal contents are elsewhere would be obnoxious. By defining the modal inline, the selection remains part of the form at all times.We're just using the language of modals to "zoom-in" on the details of one field while our user manipulates it.


Promise made and promise broken: TypeScript vs. real life data

Due to the nature of JavaScript some of these type guards are very reliable - you can easily check whether a value is a string or a number. However it is impossible to determine your function's return type or your Promise's resolution value. This is due to the fact that once you lose the information about a function signature or a promise resolution value you cannot recover it just by examining the function or Promise. Detailed summary of what can be type checked can be found in the docs.


I Promise you won't have to await long to understand async in Javascript

This is a mess! Callback hell like this was the motivation behind the Promise API, which in turn spawned the async/await API. In a moment we'll break down what this is doing, but for now let's just enjoy how clean our function looks with async/await:


Understanding JavaScript Promises and Promise Chaining in ES6

In JavaScript, a Promise is an object that may produce a value at some point in the future.


Javascript Promise 101

Knowing how Promise works in javascript will boost your development skill exponentially. Here I will share:


Testing Promise Rejection with Chai

But let's suppose that now i need my method importCustomer to be async, the snippet code above won't work, because it will return a promise and the exception that i'm expecting is coming in the Promise Rejection.


Happy JavaScript Promise coding!