简体   繁体   中英

How to prevent bind from mutating original object in node.js when using async.series?

I have the following test code:

var async = require('async');

var GROUP = 'testGroup';

var opts = {
  someKey: 'hi',
};

test(opts);

function test(options) {
  async.series([
    doThis.bind(null, options),
    doThat.bind(null, options),
  ], function(results) {
    debugger;
  });
}

function doThis(options, cb) {
  options.someKey = [GROUP, options.someKey].join('.');
  return cb();
}

function doThat(options, cb) {
  debugger;
  options.someKey = [GROUP, options.someKey].join('.');
  return cb();
}

When we hit the debugger in doThat() , options.someKey already has the value someGROUP.hi , so when the function finishes we end up with options.someKey === 'someGROUP.someGroup.hi'

How do we bind such that the original object does not change? The bind is necessary because we need to pass in options to the functions that run within async.series . Otherwise, we could just invoke the functions and pass in the object as a parameter.

I'm don't think your partially applying the options parameter to your doThis() , doThat() functions is especially pertinent.

You're passing the same javascript object/literal as aparameter to two functions and and then mutate that parameter.

If you don't to mutate that object then don't. Find some other way of returning the results of your operation. doThis() and doThat() could return values instead of modifying the parameter. You could gather them up in the final callback after the series gets called.

If you just want to preserve the intital value of opts, use lodash or something to make a deep clone of opts before you pass it into test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM