then on Objects

By  on  

Promises were a revelation in JavaScript development, allowing us to enjoy async processing and avoid callback hell. Many new APIs like Battery API, Cache API, and others use the promise API. One fact you may not know is that you can add a then method to any object to make it Promise-like!

Let's create a generic object with a then method that accepts a resolve function as its argument:

j = { then: resolve => fetch("/").then(resolve) }

With an object featuring a then method, you can call the then method or use await syntax:

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, …}

This technique is interesting and, under the right circumstances, can be employed to represent a logical usage.

Hack or useful? How would you use this perk of then?

Recent Features

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

Discussion

  1. Edgar

    Nice, although fetch may be a bad example since you would definitely want to deal with errors. But for promises of which you are sure they always resolve, it’s cool.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!