developit / greenlet

🦎 Move an async function into its own thread.
https://npm.im/greenlet
4.67k stars 100 forks source link

[Question] What is the use case for this line of code ? #20

Closed prashantagarwal closed 6 years ago

prashantagarwal commented 6 years ago

Hey Jason, Absolutely loving this library. Just of curiosity I saw this line of code. https://github.com/developit/greenlet/blob/f714faf972e89433204986e7dea7a31fdae26434/greenlet.js#L17

I am unable to correctly understand the use case here. Why can't we directly use userFunc here.

Thanks.

huwyca commented 6 years ago

@prashantagarwal that line of code is spreading the array of "proxy function" args, event.data[1], to the userFunc. The individual arguments passed to the "proxy function" got bundled into an array for postMessage on line 52. https://github.com/developit/greenlet/blob/f714faf972e89433204986e7dea7a31fdae26434/greenlet.js#L51-L58

This unbundles them without using es6 array spread syntax.

background

A lot of 3rd part promise libs, Bluebird and Q come to mind, supported a Promise.spread function that takes a fulfilled array value and turns it into individual arguments. Since the official Promise spec doesn't support Promise.spread and a Promise can only fulfill one value to the onFulfilled callback, you have to do this manually spreading to params. This is covered here under "Syntax > Parameters > onFulfilled".

example

const add = (a, b) => a + b

const spread = (userFunc) => userFunc.apply.bind(userFunc, userFunc)

const es6spread = (args) => add(...args)
// ===
const fnspread = spread(add)

es6spread([1,2]) // => 3
fnspread([1,2])  // => 3

Hope that helps!

developit commented 6 years ago

Wow, thanks for the awesome detailed explanation @huwyca!