javascript - Create handler for asynchronous code -
i'm trying create async version of eval , i'm looking method of converting or wrapping async operation doesn't supply it's own callback.
each 1 of these lines runs time-consuming operation doesn't have handler when it's done.
var fs = require('fs') settimeout(function () { throw new error ('hi') }, 3000) settimeout(function () { return 'hi' }, 3000) eval("settimeout(function () { throw new error ('hi') }, 3000)") fs.readfilesync('./package.json', 'utf8')
i know fs
has "async" counterpart fs.readfile
, example i'm interested in how i'd convert sync version async.
how craft way of wrapping 1 of these operations?
i got close doing using domain
module.
the normal try / catch
wont cut because code asyncronous.
try { settimeout(function () { throw new error ('hi') }, 3000) } catch (e) { // no error }
however can use domain
catch error, this.
var domain = require('domain') var d = domain.create(); d.on('error', function (e) { return reject(e) }) d.run(function () { settimeout(function () { throw new error ('hi') }, 3000) })
however there's no way know if function finished running , there no error.
there's talk in node community of deprecating domain
, replacing async_wrap
can't work either.
i'm looking way convert sync async (synchronous asynchronous). or more async async handler.
both bluebird
, async
have ways of converting sync code async, not async code async handler.
var _eval = require('eval') var async = require('async') var promise = require('bluebird') var _evalcallback = async.wrapsync(_eval) var _evalpromise = promise.method(_eval) var code = [ 'settimeout(function () {', ' throw "hello"', '}, 3000)' ].join('\n') _evalcallback(code, "hi.js", {}, true, function () { console.log(arguments) // => { '0': null, '1': {} } }) _evalpromise(code, "hi.js", {}, true) .then(function () { console.log(arguments) // => { '0': {} } }) .catch(function () { console.log(arguments) })
Comments
Post a Comment