Skip to content

Instantly share code, notes, and snippets.

@rainder
Last active November 22, 2017 16:50
Show Gist options
  • Save rainder/d02d52cb1eeda67aa6cf to your computer and use it in GitHub Desktop.
Save rainder/d02d52cb1eeda67aa6cf to your computer and use it in GitHub Desktop.
'use strict';
const Q = require('q')
function DeferredFnStack(fn) {
let stack = Q.when();
return () => {
const dfd = Q.defer();
stack = stack.fin(() => Q.when(fn()).then(dfd.resolve, dfd.reject));
return dfd.promise;
};
}
/**
* USAGE
*/
function asyncPromise(value) {
const dfd = Q.defer();
const resolve = () => dfd.resolve(value)
setTimeout(resolve, 500)
return dfd.promise
}
const fn = DeferredFnStack(function () {
return Q.resolve('Hello World!')
.then(asyncPromise)
.then(asyncPromise)
});
fn().then((value) => console.log(value));
fn().then((value) => console.log(value));
fn().then((value) => console.log(value));
/*
Outputs 3 times 'Hello World!' with 1000ms interval
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment