Skip to content

Instantly share code, notes, and snippets.

@martynchamberlin
Last active June 12, 2017 11:46
Show Gist options
  • Save martynchamberlin/2603ad6620c7c04bd2714acd21eaf4db to your computer and use it in GitHub Desktop.
Save martynchamberlin/2603ad6620c7c04bd2714acd21eaf4db to your computer and use it in GitHub Desktop.
JavaScript ES6 Promises Example

Let's say we want to call a function that does some work, then we want to do our own work, then let the function know that we've completed our work. We could achieve that by doing this:

var s = () => {
  console.log('start');
  return Promise.resolve(() => { console.log('run after finish') });
};


const start = s();
console.log('then do work');
start.then(f => f());

This will print in the following order:

start
then do work
run after finish

Obviously you don't have to use promises for this though. In fact, I wouldn't recommend it. Just return the object you want to run.

var s = () => {
  console.log('start');
  return { finish: () => { console.log('run after finish') } };
};


const work = s();
console.log('then do work');
work.finish();
class PromiseExample {
  constructor() {
    this.promise = new Promise((resolve, reject) => {
      this.resolve = resolve;
    });
  }
  
  resolveThat(data) {
    this.resolve(data);
  }
  
  someLaterMethod() {
    this.promise.then((data) => { console.log(data) });
  }
}

And then this:

const example = new PromiseExample();
example.resolveThat('hello');
example.someLaterMethod(); // logs "hello" to the console

But also this, demonstrating that the order doesn't matter:

const example = new PromiseExample();
example.someLaterMethod(); 
example.resolveThat('hello'); // logs "hello" to the console
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment