Skip to content

Instantly share code, notes, and snippets.

@co3moz
Last active May 7, 2018 16:10
Show Gist options
  • Save co3moz/ccf6dea96030866ed24313f2b046fb0b to your computer and use it in GitHub Desktop.
Save co3moz/ccf6dea96030866ed24313f2b046fb0b to your computer and use it in GitHub Desktop.
primitive asyncMap and asyncForeach methods for primitive environment
function asyncForeach(array, fn, atEnd) {
var at = -1;
function next(shouldBreak) {
if (shouldBreak || ++at == array.length) {
if (atEnd) {
setTimeout(atEnd);
}
} else {
setTimeout(fn, 0, array[at], next);
}
}
next();
}
function asyncMap(array, fn, atEnd) {
var at = -1;
var temp = new Array(array.length);
function next(value, shouldBreak) {
if (at != -1) temp[at] = value;
if (shouldBreak || ++at == array.length) {
if (atEnd) {
setTimeout(atEnd, 0, temp);
}
} else {
setTimeout(fn, 0, array[at], next);
}
}
next();
}
asyncForeach([1, 2, 3], function (item, done) {
console.log('item: ', item);
setTimeout(done, 1000);
}, function () {
console.log('end');
})
asyncMap([1, 2, 3], function (item, done) {
console.log('item: ', item);
setTimeout(done, 1000, item * 2);
}, function (array) {
console.log('end', array);
})
// break the loop
asyncForeach([1, 2, 3], function (item, done) {
console.log('item: ', item);
done(true);
}, function () {
console.log('end');
});
asyncMap([1, 2, 3], function (item, done) {
console.log('item: ', item);
done(item * 2, true);
}, function (array) {
console.log('end', array);
})
function sync() {
var i = 0;
var arr = [];
return {
begin: function () {
i++;
},
end: function () {
return new Promise(function (resolve) {
arr.push(resolve);
i--;
if (i == 0) {
arr.forEach(function (x) { x(); });
}
});
}
}
}
//example
var s = sync();
for (var i = 0; i < 5; i++) {
(async function (i) {
s.begin();
console.log(i, 'begin');
await new Promise(x => setTimeout(x, i*750));
console.log(i, 'ready');
await s.end();
console.log(i, 'play');
})(i)
}
//0 "begin"
//1 "begin"
//2 "begin"
//3 "begin"
//4 "begin"
//0 "ready"
//1 "ready"
//2 "ready"
//3 "ready"
//4 "ready"
//0 "play"
//1 "play"
//2 "play"
//3 "play"
//4 "play"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment