5 Awesome JavaScript Promise Tricks

Image for post
Image for post

Promises are a big invention of javascript. Previously we usesetTimeouts and settling for synchronous operations to doing everything possible to leverage this new async API. Let's check out a handful of awesome Promises tricks!

One problem we instantly complained about with promises was not being able to cancel them. A simple promiseInstance.cancel() would have been excellent but never came. Instead, we were given an API that was way more complicated:

const controller = new AbortController();
const { signal } = controller;
fetch("http://localhost:8000", { signal }).then(response => {
console.log(`Request 1 is complete!`);
}).catch(e => {
console.warn(`Fetch 1 error: ${e.message}`);
// Abort request

The magic here is providing the signal with each fetch request. In the JavaScript world, we inherit difficult APIs and do wonders to abstract them, and thus we'll find a way to better abstract this API.

Waiting for a duration is useful in loads of production and testing situations — it’s never ideal but always helpful. I’ve used two awesome functions to make my life better:

/* Wait for milliseconds */
function waitForTime(ms) {
return new Promise(r => setTimeout(r, ms));
/* Usage */
await waitForTime(200);
/* Wait Forever */
function waitForever() {
return new Promise(r => {});
// Usage:
await waitForever();

Don’t wait for perfect situations, wait for the time you need.

Array functions like forEach, map, and other functions are used frequently without the need for them to be synchronous. We don't think about it there's a fair amount of times we can go async with our operations.

const promises = [1, 2, 3].map(async (num) => {
await promises;

The difference in caring between async and sync is Promise.allSettled. Go async when you can!

Did you know that you can arbitrarily add a then method on objects to have them treated as a Promise?

j = { then: resolve => fetch("/").then(resolve) }j.then(res => console.log(res));
// Response {type: "basic", url: "https://davidwalsh.name/", redirected: false, status: 200, ok: true, …}
// ... or an await...
const response = await j;
// Response {type: "basic", url: "https://davidwalsh.name/", redirected: false, status: 200, ok: true, …}

Now you know! An excellent trick most don’t know about!

Not something you would need to do often but this post is about tricks, right? If you want to detect an asynchronous function, you always can:

async function myFunction() {}const isAsync = myFunction.constructor.name === "AsyncFunction";

JavaScript Promises are something we every day but a broader look at them allows us to innovate! Have any Promise tricks of your own? Share it with me.

Source- https://davidwalsh.name/javascript-promise-tricks

If you love this article help me to buy a coffee: https://www.buymeacoffee.com/harry1408

Harsh Patel | Full-Stack Developer | http://imharshpatel.com

Written by

🤠 Internet Cowboy | 💻 JS Aficionado | http://imharshpatel.com/

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