Skip to content

Instantly share code, notes, and snippets.

@badmonster0
Last active August 29, 2015 14:20
Show Gist options
  • Save badmonster0/3ba92e73ff5d21d696b9 to your computer and use it in GitHub Desktop.
Save badmonster0/3ba92e73ff5d21d696b9 to your computer and use it in GitHub Desktop.
nodeify spread:true explaination

run bode

let promise = Promise.resolve([false, 'error message'])
let nodeify = require('bluebird-nodeify')
nodeify(promise, console.log) 
# output null [ false, 'error message' ]
nodeify(promise, console.log, {spread:true});
#output null false 'error message'

In the some cases, you would expect callback in multiple arguments.

For instance when you use passport, and create a simple strategy like this. In passport "done" function, we need multiple arguments

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;
  
let userConst = {
		email: '[email protected]',
		password: bcrypt.hashSync('asdf', SALT)
}

passport.use('local-simple', new LocalStrategy(
  function(username, password, done) {
      if (err) { return done(err); }
      if (email !== userConst.email) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (password !== userConst.passport) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      //we have to return user here.
      return done(null, user);
  }
));

Here done(null, false, { message: 'Incorrect username.' }) takes three separate arguements.

When you write it in async mode, and use nodeify to pass callback, you would write something like

let userConst = {
		email: '[email protected]',
		password: bcrypt.hashSync('asdf', SALT)
}
passport.use('local-simple', new LocalStrategy({
    // Use "email" field instead of "username"
    usernameField: 'email'
}, (email, password, callback) => {
    nodeify(async() => {
        if (email !== userConst.email) {
            return [false, {
                message: 'Invalid username'
            }]
        }

        if (!await bcrypt.promise.compare(password, userConst.password)) {
            return [false, {
                message: 'Invalid password'
            }]
        }
        //after you return
        //it becomes req.user
        //otherwise you won't have anything
        return userConst

        // Use spread option when returning multiple values
        // use spread
        // so a callback gets convert from [1,2] => callback(null, 1, 2)
        // without spread:true, it becomes   [1, 2] => callback(null, [1, 2])
    }(), callback, {
        spread: true
    })
}))

using spread, it will make sure your callback is called with multiple arguments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment