Write algorithms that can be re-used for synchronous and asynchronous code
Write algorithms that can be re-used for synchronous and asynchronous code using promises and
npm install alagator
var path = require'path'var fs = require'fs'var Promise = require'promise'var alagator = require'alagator'moduleexports = mkdirpFactorytrue Promisedenodeifyfsmkdir Promisedenodeifyfsstatmoduleexportssync = mkdirpFactoryfalse fsmkdirSync fsstatSyncmoduleexportsmkdirp = moduleexportsmkdirP = moduleexportsvar rec = alagatorif mode ===mode = 0777 & ~processumask;if !made made = null;if typeof mode === 'string' mode = parseIntmode 8;p = pathresolvep;tryyield mkdirp mode;made = made || p;catch err0switch err0codecase 'ENOENT' :made = yield recpathdirnamep mode made;yield recp mode made;break;// In the case of any other error, just see if there's a dir// there already. If so, then hooray! If not, then something// is borked.default:var stat;trystat = yield statp;catch err1throw err0;if !statisDirectory throw err0;break;return made;asyncreturn rec
isAsync defaults to
alagator method takes a generator function, and then either
true (for async) or
false (for sync). If
false is passed, it makes
yield act as a pass through, so the method runs fully synchronously. If
true is passed, it makes
yield await the resolution of a promise (or array of promises) so that the function becomes async (it also uses
Promise.nodeify to support both callback and promise based use). The above mkdirp example could be used in any of the following 3 ways:
var mkdirp = require'mkdirp'mkdirp'/foo/bar'if err throw errconsole.log'/foo/bar exists'//ormkdirp'/foo/bar'thenconsole.log'/foo/bar exists'done//ormkdirpsync'/foo/bar'console.log'/foo/bar exists'
Exactly as above, except the function is immediately called with no arguments.
If you want the promise returned from async versions of your algorithms to be of a specific type (other than promise) we've got you covered. Simply pass a wrap function in place of
var Q = require'q'moduleexports = mkdirpFactoryQ Qdenodeifyfsmkdir Qdenodeifyfsstatmoduleexportssync = mkdirpFactoryfalse fsmkdirSync fsstatSync
This will still make use of the same promise library internally, but externally will exclusively use Q.