Skip to content

mfilenko/js-idioms

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Idiomatic JavaScript

A collection of tips and tricks I saw online that helps to write idiomatic JavaScript. Please, feel free to submit your pull requests to add more.

Table of Contents

Objects

Helpers

  • Delay 'polyfill':

    const wait = (timeout) => (new Promise(resolve => setTimeout(resolve, timeout)));

    Usage:

    // Promises
    wait(500).then(() => doSomething());
    
    // async/await
    await wait(500);
    doSomething();

    Source: https://twitter.com/JakeDohm/status/1118973133443207179

  • Go-like results handling1:

    function O_o(promise) {
      return promise.then(data => {
        if (data instanceof Error) return [data];
        return [null, data];
      }).catch(err => [err]);
    }
    
    // Usage:
    async function usageExample(params) {
      const [err, data] = await O_o(myPromise(params));
    
      if (err) {
        // Handle or throw.
      }
    
      // Do stuff with data.
      return data;
    }

    Source: https://twitter.com/davidwells/status/1119729914876284928

Footnotes

  1. Not quite idiomatic, but still cool and useful :-)

Releases

No releases published

Packages

No packages published