简体   繁体   中英

Pass extra variable to callback function

I am trying to create a simple method that logs out my DB operation results in a prettified format in the console. I want to pass an extra variable ( operationName ) to my custom logger callback function when my DB finishes an operation.

 // Custom logger (simplified) const dbLogger = (error, data, operationName) => { if (error) { console.log(`${operationName} failed`, error) } console.log(`${operationName} success`, data) } // mongodb operations import ChatModel from 'somewhere'; function createMessage() { const newChatAdded = new ChatModel({ message: 'Hi' }) ChatModel.save(newChatAdded, dbLogger); } 

Here the error and data in our callback is provided by the ChatModel.save method but I want to send a 3rd parameter operationName (eg. 'save' or 'delete') as well.

Two ways, take your pick!

  1. use anonymous function with a rest parameter and spread these on calling dbLogger :

     ChatModel.save(newChatAdded, (...args) => dbLogger(...args, "save"); 
  2. use a bound function :

    Change your dbLogger function signature to accept operationName as the first argument:

     const dbLogger = (operationName, error, data) => { if (error) { console.log(`${operationName} failed`, error) } console.log(`${operationName} success`, data) } 

    Create new bound log function which will always be called with "save" as the first argument.

     ChatModel.save(newChatAdded, dbLogger.bind(null, "save"); 

    This is also called "partial application" .

ChatModel.save(newChatAdded, (error, data) => dbLogger(error, data, 'save'));

If you'd change the order of your parameters, you could make that more succinct:

const dbLogger = (operationName, error, data) => ...

ChatModel.save(newChatAdded, dbLogger.bind(null, 'save'));

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