Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better understanding javascript's yield

I have the following code in my Koa app:

exports.home = function *(next){
  yield save('bar')
}

var save = function(what){
  var response = redis.save('foo', what)
  return response
}

But I get the following error: TypeError: You may only yield a function, promise, generator, array, or object, but the following object was passed: "OK"

Now, "ok" is the response from the redis server, which makes sense. But I cannot fully grasp the concept of generators for this kinds of functions. Any help?

like image 295
john doe Avatar asked May 15 '26 21:05

john doe


1 Answers

You don't yield save('bar') because SAVE is synchronous. (Are you sure you want to use save?)

Since it's synchronous, you should change this:

exports.home = function *(next){
  yield save('bar')
}

to this:

exports.home = function *(next){
  save('bar')
}

and it will block execution until it's finished.

Almost all other Redis methods are asynchronous, so you would need to yield them.

For example:

exports.home = function *(next){
  var result = yield redis.set('foo', 'bar')
}
like image 126
danneu Avatar answered May 17 '26 11:05

danneu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!