xpt
xpt

Reputation: 23036

Why bind function stop working in this case for NodeJS

Why bind function stops working for the following code?

function exitHandler(options, err) {
  console.log('exit');
  if (options.cleanup) console.log('clean');
  if (err) console.log(err.stack);
  if (options.exit) process.exit();
}

//do something when app is closing
//process.on('exit', exitHandler.bind(null,{cleanup:true})); process.exit()

// or
process.on('exit', function() {
  exitHandler.bind(null,{cleanup:true})
});

If I un-comment the process.on('exit', exitHandler.bind... line, it'd work fine.

Upvotes: 0

Views: 267

Answers (2)

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

Are you sure it is bind and not call what you want:

  function exitHandler(options, err) {
    console.log('exit');
    if (options.cleanup) console.log('clean');
    if (err) console.log(err.stack);
    if (options.exit) process.exit();
  }

  process.on('exit', function() {
    exitHandler.call(null,{cleanup:true})
  });

EDIT:

If you are not using the context (this) you could call the function normally:

exitHandler({cleanup:true});

Upvotes: 1

E. Sundin
E. Sundin

Reputation: 4180

I think it's because the bind creates a new function so in your second example it does not actually fire the function. In the first case it does get fired.

Upvotes: 1

Related Questions