Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of using the co library with promises instead of with thunks?

So I've been reading about the usage of the co library, and the general design pattern I've seen in most blog posts is wrapping functions that have callbacks in thunks. Then using an es6 generator to yield those thunks to the co object. Like this:

co(function *(){
  var a = yield read(‘Readme.md’);
  var b = yield read(‘package.json’);
  console.log(a);
  console.log(b);
});
function read(path) {
  return function(done){
    fs.readFile(path, ‘utf8', done);
  }
}

And that I can understand because it brings all the benefits of promises like better readability and better error handling.

But what's the point of using co if you already have promises available?

co(function* () {
  var res = yield [
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.resolve(3),
  ];
  console.log(res); // => [1, 2, 3]
}).catch(onerror);

Why not something like

Promise.all([
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.resolve(3),
]).then((res) => console.log(res)); // => [1, 2, 3]
}).catch(onerror);

To me, co makes the code look more confusing compared to the Promise version.

like image 747
m0meni Avatar asked Jan 05 '16 21:01

m0meni


1 Answers

No real cases, no. Unless you really hate the promise constructor (in which case, bluebird promisify to the rescue).

When you have Promises natively, nearly all valid usecases for callbacks that are called once with a single value are effectively moot.

like image 55
Madara's Ghost Avatar answered Oct 07 '22 22:10

Madara's Ghost