0

I have tried a few combinations of the below to no effect. I simply want to pause execution and return to the router function when ready and then release the response. Is this possible?

var express = require('express');
var router = express.Router();
var request = require('request');

router.get('/', function(req, res, next) {

    var result = getJson();

    res.render('index', { title: result});

});


function *getJson(){
    yield request('https://myjson.json', function (error, response, body){
        return body;
    });
}




module.exports = router;
Exitos
  • 29,230
  • 38
  • 123
  • 178
  • you're yielding the return of request(), not `body` being returned inside of it. – Kevin B May 26 '15 at 20:38
  • 1
    I don't see any simple and clean way to use yield here (ugly convoluted ways are described [here](http://davidwalsh.name/async-generators)). Promises are probably the solution you need until ES7. – Denys Séguret May 26 '15 at 20:46
  • If you just want the JSON to be sent back just put the `res.render` into the `request` callback. You don't need to yield anything, unless you have some higher-level end goal, let the event loop handle it. – Tony May 26 '15 at 20:52
  • You could use a generator for this like this: http://jsfiddle.net/oybcq94g/ however that likely defeates the purpose of what you're trying to accomplish. – Kevin B May 26 '15 at 21:10

1 Answers1

0

What you are looking for is async/await, not yield. yield is used when you want to enumerate. You can read more about it on Mozilla Developer Network and this SO answer.

async/await are both ECMAScript 7 language features, so they are not available natively in the browsers yet. You could use the Traceur compiler to translate/compile/transpile ES7 code into ES5 code, but I haven't tried it. An example can be found here.

It is possible to use generators and yield in a similar manner to async/await, check out this article by Jake Archibald for the details.

Community
  • 1
  • 1
Jim Buck
  • 2,383
  • 23
  • 42
  • oh rubbish it will be years until that is implemented then? – Exitos May 26 '15 at 20:45
  • Since you are using NodeJS, you might be able to use https://github.com/yortus/asyncawait. Or just use Traceur to compile the ES7 code into something usable today, which also works in the browser! – Jim Buck May 26 '15 at 20:47