Skip to content

Instantly share code, notes, and snippets.

@dallonf
Created November 13, 2012 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dallonf/4067893 to your computer and use it in GitHub Desktop.
Save dallonf/4067893 to your computer and use it in GitHub Desktop.
AwaitScript compiler concept
// AwaitScript sample compiled to JavaScript
var async = require('async');
function recurse(path, fn) {
var files = [];
fs.readdir(path, function(err, dir) {
if (err) return fn(err);
async.forEach(dir, function(f, fn) {
fs.stat(f, function(err, stat) {
if (err) return fn(err);
if (stat.isFile()) {
files.push(f);
__afterIf1__();
} else {
recurse(path, function(err, recursiveFiles) {
if (err) return fn(err);
Array.prototype.push.apply(files, recursiveFiles);
__afterIf1__();
});
}
function __afterIf1__ (err) {
if (err) return fn(err);
__after__();
}
});
function __after__(err) {
if (err) return fn(err);
return fn(null, files);
}
}, __after1__);
});
function __after__(err) {
if (err) return fn(err);
return fn(null, files);
}
}
try {
recurse('.', __try1__);
} catch (e) {
__catch1__(e);
}
function __try1__ (err) {
if (err) return __catch1__(err);
__finally1__();
}
function __catch1__ (err) {
console.error(e);
__finally1__();
}
function __finally1__() {
console.log('and done...');
__afterTry1__();
}
function __afterTry1__(err) {
if (err) throw err;
console.log(files);
}
// the magic way that could maybe work with await
var async = require('async'); // async library is actually improved by await
async function recurse(path) {
var files = [];
// Awaits can only be variable assignments
// Later versions might support anonymous awaits
var dir = await fs.readdir(path);
await async.forEach(dir, async function(f) {
var stat = await fs.stat(f);
if(stat.isFile()) {
files.push(f);
} else {
var recursiveFiles = await recurse(path);
Array.prototype.push.apply(files, recursiveFiles);
}
});
return files;
}
await async try {
await recurse('.');
} catch(e) {
// same scope, not same tick
console.error(e);
} finally {
console.log('and done...');
}
console.log(files);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment