Node.js async to sync

后端 未结 5 1016
走了就别回头了
走了就别回头了 2020-12-13 19:44

How can I make this work

var asyncToSync = syncFunc();

function syncFunc() {
    var sync = true;
    var data = null;
    query(params, function(result){
          


        
5条回答
  •  温柔的废话
    2020-12-13 20:09

    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
    

提交回复
热议问题