As you wrote it Tokens.create will not return your token; it will return 
undefined! The return token statement is inside the callback, not inside 
Tokens.create.

To make this work you have to turn Tokens.create into an async function and 
call it with a callback:


    Tokens.create(function(ex, token) {
      if (ex) throw ex;
      pair(email, token);
      send(email, token);
    });
    
    Tokens.create = function(cb) {
      crypto.randomBytes(48, function(ex, buf) {
        if (ex) return cb(ex);
        var token = buf.toString('hex');
        cb(null, token);
      })
    }

Async is contagious: if a function needs a value which is returned 
asynchronously by another function, it must be asynchronous.

Bruno

On Monday, July 13, 2015 at 7:59:49 AM UTC+2, sam wrote:
>
>
> ```
> /* somewhere deep inside a module... */
> var token = Tokens.create();
> pair(email, token);
> send(email, token); 
> ```
>
> ```
> /* in another module */
> Tokens.create = function() {
>   crypto.randomBytes(48, function(ex, buf) {
>     var token = buf.toString('hex');
>     return token;
>   })
> }
> ```
>
> Will the `Tokens.create()` be ran in parallel to `pair(email, token)` and 
> `send(token, email)`? I'm trying to understand if i need to use a callback 
> or not here
>
> Someone in IRC responded:
> "just google for callbacks, in a nutshell when the second argument of 
> function is a function"
>
> Tokens.create doesn't take a callback, but the function it calls, 
> `crypto.randomBytes`, does. So will `token = Tokens.create` be ran 
> asynchronously?
>
>

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/a40043da-daa4-4fe9-8f74-052619d620c2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to