Node.js 异步同步
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16586640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js async to sync
提问by user840250
How can I make this work
我怎样才能使这项工作
var asyncToSync = syncFunc();
function syncFunc() {
var sync = true;
var data = null;
query(params, function(result){
data = result;
sync = false;
});
while(sync) {}
return data;
}
I tried to get sync function from async one, I need it to use FreeTds async query as sync one
我试图从 async one 获取同步功能,我需要它使用 FreeTds 异步查询作为同步 one
采纳答案by abbr
Use deasync- a module written in C++ which exposes Node.js event loop to JavaScript. The module also exposes a sleepfunction that blocks subsequent code but doesn't block entire thread, nor incur busy wait. You can put the sleepfunction in your whileloop:
使用deasync- 一个用 C++ 编写的模块,它将 Node.js 事件循环暴露给 JavaScript。该模块还公开了一个sleep函数,该函数会阻塞后续代码但不会阻塞整个线程,也不会导致忙等待。您可以将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;
}
回答by drodsou
Nowadays this generator pattern can be a fantastic solution in many situations:
如今,这种生成器模式在许多情况下都可以成为绝佳的解决方案:
// 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
回答by Dmitry Manannikov
You can do it with node-sync lib
您可以使用节点同步库来完成
var sync = require('sync');
sync(function(){
var result = query.sync(query, params);
// result can be used immediately
})
Notice: your query must use standart callback call (with error first): callback(error, result). If you can't change query method, just create .async() wrapper (see github link).
注意:您的查询必须使用标准回调调用(错误优先):回调(错误,结果)。如果您无法更改查询方法,只需创建 .async() 包装器(请参阅 github 链接)。
回答by shellscape
I've been using syncrhonize.jswith great success. There's even a pending pull request (which works quite well) to support async functions which have multiple parameters. Far better and easier to use than node-sync imho. Added bonus that it has easy-to-understand and thorough documentation, whereas node-sync does not.
我一直在使用syncrhonize.js并取得了巨大的成功。甚至还有一个挂起的拉取请求(效果很好)来支持具有多个参数的异步函数。imho 比 node-sync 更好也更容易使用。额外的好处是它具有易于理解和详尽的文档,而 node-sync 则没有。
回答by Maus
The issue you are having is that your tight while loop is blocking. So I don't think your query callback will ever be run. I think you need to use setTimeout or the like to prevent the function from blocking, but should you do so, the function will return before the callback is called. This functionality must be implemented at a lower level.
您遇到的问题是您的 while 循环被阻塞了。所以我认为您的查询回调永远不会运行。我认为您需要使用 setTimeout 等来防止函数阻塞,但如果您这样做,该函数将在调用回调之前返回。此功能必须在较低级别实现。
If you are in the browser, you might check out this article. In node you have to rely on the implementation of whatever you're querying. It may or may not provide synchronous methods.
如果您在浏览器中,您可能会查看这篇文章。在节点中,您必须依赖于您正在查询的任何内容的实现。它可能提供也可能不提供同步方法。

