Node.jsasynchronous同步

我怎样才能做这个工作

var asyncToSync = syncFunc(); function syncFunc() { var sync = true; var data = null; query(params, function(result){ data = result; sync = false; }); while(sync) {} return data; } 

我试图从asynchronous获得同步function,我需要它使用FreeTdsasynchronous查询作为同步

使用deasync – 用C ++编写的一个模块,它将Node.js事件循环暴露给JavaScript。 该模块还公开了一个sleepfunction,阻止后续代码,但不会阻塞整个线程,也不会忙于等待。 你可以把sleep函数放在while循环中:

 var asyncToSync = syncFunc(); function syncFunc() { var sync = true; var data = null; query(params, function(result){ data = result; sync = false; }); while(sync) {require('deasync').sleep(100);} return data; } 

你可以用node-sync lib来完成

 var sync = require('sync'); sync(function(){ var result = query.sync(query, params); // result can be used immediately }) 

注意:您的查询必须使用标准callback调用(首先出现错误):callback(错误,结果)。 如果您不能更改查询方法,只需创build.async()包装(请参阅github链接)。

如今,这种发生器模式在许多情况下可以是一个绝佳的解决scheme:

 // nodejs script doing sequential prompts using async readline.question function var main = (function* () { // just import and initialize 'readline' in nodejs var r = require('readline') var rl = r.createInterface({input: process.stdin, output: process.stdout }) // magic here, the callback is the iterator.next var answerA = yield rl.question('do you want this? ', res=>main.next(res)) // and again, in a sync fashion var answerB = yield rl.question('are you sure? ', res=>main.next(res)) // readline boilerplate rl.close() console.log(answerA, answerB) })() // <-- executed: iterator created from generator main.next() // kick off the iterator, // runs until the first 'yield', including rightmost code // and waits until another main.next() happens 

我一直在使用syncrhonize.js ,取得了巨大的成功。 甚至还有一个挂起的请求(工作得很好)来支持具有多个参数的asynchronous函数。 比节点同步imho更好,更容易使用。 增加了奖励,它有易于理解和详尽的文档,而节点同步不。

你遇到的问题是你的紧张的循环被阻止。 所以我不认为你的查询callback将永远不会运行。 我认为你需要使用setTimeout或类似的东西来防止函数阻塞,但是如果你这样做,函数将在调用callback之前返回。 这个function必须在较低的层次上实现。

如果你在浏览器中,你可以看看这篇文章 。 在节点中,你必须依赖你正在查询的任何东西的实现。 它可能提供或不提供同步方法。