Skip to content

Instantly share code, notes, and snippets.

@patrixr
Created November 13, 2020 02:32
Show Gist options
  • Save patrixr/b1227b77aa02855104d26549f6075e86 to your computer and use it in GitHub Desktop.
Save patrixr/b1227b77aa02855104d26549f6075e86 to your computer and use it in GitHub Desktop.
const RSVP = require('rsvp');
const Ember = { RSVP };
/**
* Returns a promise and a trigger to start the job
*
* @export
* @param {Function} func the job to execute
* @param {any} scope the scope to bind the function to
* @param {...any} args arguments
* @returns {array} [promise, job]
*/
function useDefer(func, scope, ...args) {
const deferred = Ember.RSVP.defer();
const trigger = async () => {
try {
const res = await func.apply(scope, args);
deferred.resolve(res);
} catch (e) {
deferred.reject(e);
}
}
return [deferred.promise, trigger]
}
/**
* Returns a function that cannot run in parallel, any subsequent call will be queued
*
* @export
* @param {function} func
* @returns {function} a queued version of func
*/
function queued(func) {
let queue = [];
const next = async () => {
if (queue.length) {
await queue[0]();
queue.shift();
next();
}
};
return function (...args) {
const [promise, job] = useDefer(func, this, ...args);
queue.push(job);
if (queue.length === 1) {
next(); // start
}
return promise;
};
}
const waitFor = queued(async (time) => {
return new Ember.RSVP.Promise((done) => {
setTimeout(() => {
console.log('done after ' + time + 'ms');
done();
}, time);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment