0

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 Answers1

0

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?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Do you mean a thunk in the context of coroutines always expects a continuation? That would make sense. –  Nov 24 '18 at 12:56
  • `res(res)` was indeed my fault, when I thoughtless used `find/replace all` in sublime. Sorry for that! –  Nov 24 '18 at 12:58
  • @reify Yes, a thunk is a value that needs a continuation. – Bergi Nov 24 '18 at 14:27