在node.js中编写同步函数的简单方法

出于testing的目的,如果我能够执行一些等待同步的testing函数来获得结果,我的代码将会看起来更好。

我知道关于node.js中事件编程的主要思想,但是在同步运行的testing中,处理器对我来说不是问题。

是否有任何简单的(单线程将是最好的)解决scheme来执行函数,通过callback(err,ret)返回一些值,通过“return”返回该ret,并假装执行是同步的。

你可以使用节点同步来达到这个目的https://github.com/0ctave/node-sync

但总的来说,我build议你不要。 摩卡testing框架,例如允许你做asynchronoustesting。 另外asynchronous瀑布https://github.com/caolan/async#waterfall是一个很好的方式来伪代码同步。

我会说停留在asynchronous思维框架。 即使在testing。

摩卡有内置的donecallback函数来实现这一点。 我用于我的代码的模式:

 describe('some spec', function () { beforeEach(function (done) { // common spec initalization code.. common.init (function (err, stuff) { done(err); }); }); describe('particular case', function () { var result, another; beforeEach(function (done) { // case init 1.. case.init(function (err, res) { result = res; done(err); }); }); beforeEach(function (done) { // case init 2.. case.init2(function (err, res) { another = res; done(err); }); }); it ('should be smth', function () { expect(result).to.equal(0); }); it ('should be smth else', function () { expect(another).to.equal(1); }); }); });