Node.js异步同步

use*_*250 23 javascript asynchronous node.js

我怎样才能做到这一点

var asyncToSync = syncFunc();

function syncFunc() {
    var sync = true;
    var data = null;
    query(params, function(result){
        data = result;
        sync = false;
    });
    while(sync) {}
    return data;
}
Run Code Online (Sandbox Code Playgroud)

我试图从异步中获取同步功能,我需要它使用FreeTds异步查询作为同步功能

abb*_*bbr 20

使用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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是您不必在光纤内运行的唯一一个(如果您不控制调用代码,则不能总是这样做) (3认同)

dro*_*sou 10

如今,这种发生器模式在许多情况下都是一个很棒的解决方案:

// 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
Run Code Online (Sandbox Code Playgroud)

  • 这在主函数之外仍然是异步的,如果你把`console.log("EOF")`放在最后一行,你会看到`你想要这个吗?立即 EOF`。这实际上是一个手工制作的“async/await”实现 (2认同)

Dmi*_*kov 9

您可以使用node-sync lib来完成此操作

var sync = require('sync');

sync(function(){
  var result = query.sync(query, params);
  // result can be used immediately
})
Run Code Online (Sandbox Code Playgroud)

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