What is the purpose of thunkToPromise in the co coroutine lib?

47 Views Asked by At

I know co is kind of outdated but I am still interested in how it works. I find it hard to understand the purpose of the thunkToPromise function, though:

function thunkToPromise(fn) {
  var ctx = this;
  return new Promise(function (res, rej) {
    fn.call(ctx, function (err, res) {
      if (err) return rej(err);
      if (arguments.length > 2) res = slice.call(arguments, 1);
      res(res);
    });
  });
}

A thunk is a function without parameters, but fn is still called with one argument. In addition there is this weird recursive call res(res), which usually results in a stack overflow. What's going on here? How would I apply thunkToPromise so that it does something meaningful?

1

There are 1 best solutions below

3
On BEST ANSWER

A thunk is a function without parameters

No. A thunk is a function that takes only a callback to forward its result. It does take no data parameters, that's true, only an "output parameter".

In addition there is this weird recursive call res(res)

It's not recursive, it's just broken. Someone mixed up result and resolve. Did you find this in a current release of the library?