js generator for asynchronous function

How to use yield in a nested function?

function* translate(){
    socket.once( 'translate/set', function( data){
        yield data
    });

    socket.emit( 'translate/get', { query: query})
};


var data = translate().next().value;
console.log( data);

Error

  • RequireJS not working in IE9
  • Benchmark Asynchronous Code (Benchmark.js, Node.js)
  • When does an async task start in javascript?
  • How do I know when the last async is done?
  • Firebase Callbacks - what's the underlying trigger?
  • binding this keyword on anonymous & async function
  • yield is not defined
    

    I do not understand how to use the generator to an asynchronous function, without changing their code

  • JavaScript asynchronous race condition
  • How do I return the response from an asynchronous call?
  • Retrieve parsed data from CSV in Javascript object (using Papa Parse)
  • How to sequence groups of async functions without nesting (jquery $.when .then)
  • Why did wrapping my JavaScript library in an anonymous function fix my race condition?
  • Async function nested within async.js waterfall
  • One Solution collect form web for “js generator for asynchronous function”

    You cannot yield outside of a generator’s immediate inner context. What you can do however is pass a callback to translate, yield the call to socket.once (giving it the callback), and then continue execution of translate once this callback is invoked.

    function* translate(cb){
        yield socket.once('translate/set', cb);
        socket.emit('translate/get', {query: query})
    }
    
    var translate = translate(cb);
    translate().next(); // ...socket#once
    
    function cb(data) {
        console.log(data); // data from socket#once
        translate.next(); // ...socket#emit
    }