wilk / microjob

A tiny wrapper for turning Node.js worker threads into easy-to-use routines for heavy CPU loads.
https://wilk.github.io/microjob/
MIT License
2.02k stars 47 forks source link

Functions in nested objects are not passed. #57

Closed CatsMiaow closed 4 years ago

CatsMiaow commented 4 years ago
const ctxPass = { foo: 'bar', func: () => 'this is func' };

// Working, but I'm confused because it doesn't match the parent variable name.
await job(() => {
  // @ts-ignore
  return func();
}, { ctx: ctxPass });

// Not Working
await job(() => {  
  return ctxPass.func();
}, { ctx: { ctxPass } });

https://github.com/wilk/microjob/blob/master/src/worker-pool.ts#L89 The function disappears from JSON.stringify.

const ctx = {
  test: { depth: { foo: 'bar', func: () => 'this is func' } },
  testFunc: () => 'testFunc()' };

function convert(ctx) {
  let ret = '{';
  for (let [key, val] of Object.entries(ctx)) {
    if (typeof val === 'function') {
      val = val.toString();
    } else if (Array.isArray(val)) {
      val = JSON.stringify(val);
    } else if (typeof val === 'object') {
      val = convert(val);
    } else {
      val = `'${val}'`;
    }

    ret += `${key}:${val},`;
  }
  ret += '}';

  return ret;
}

console.log(`let test = ${convert(ctx)}`);
// let test = {test:{depth:{foo:'bar',func:() => 'this is func',},},testFunc:() => 'testFunc()',}

Reference https://stackoverflow.com/a/57668208

What do you think about this?

wilk commented 4 years ago

Hi @CatsMiaow,

Thanks for this issue! Actually, this is how microjob works right now but, no, I don't like it either. The context is passed as global, with no reference with the outer scope and that sucks. I'd like to refactor this part and let the user using a local variable to refer to it.

This regards also this PR: https://github.com/wilk/microjob/pull/51

CatsMiaow commented 4 years ago

Thank you for answer. I hope the #48, #51 PRs are reviewed.