Question

I've read through a number of examples and tutorials and although I know the solution is probably simple I just can't get my brain wrapped around it. Any help here would be really appreciated.

I have two functions in Node. functionA() takes no arguments and returns a string in English. The second, functionB(english) takes the English string returned from functionA() and translates it to another language.

I believe that a callback is the best solution here but for the life of me I can't figure out what the best structure would be.

Was it helpful?

Solution

I'm a little unclear as to what you're looking to do (you might be overthinking things) but consider the following which illustrates four ways of these functions being called and calling amongst themselves. As a clarification, I should note that I am not writing node-style callbacks, which always take the form callback(err,result) in which err evaluates to false if there is no error. You don't have to write your own callbacks that way, although I tend to do so myself.

// your 'functionA'
function getMessage(){
    return 'Hello';
};

// your 'functionB'
function francofy(str) {
    var result;
    switch(str){
        case 'Hello':
            result = 'Bon jour'; // 'Allo' might be better choice, but let's stick to node
            break;
        default:
            throw new Error('My Vocabulary is too limited');
    }
    return result;
};

// the most straightforward use of these functions

console.log('Synch message, synch translate', francofy(getMessage()));

// what if the translation is asynch - for example, you're calling off to an API 
// let's simulate the API delay with setTimeout
function contemplateTranslation(str,cb) {
    setTimeout(function(){
        var result = francofy(str);
        cb(result);
    },1000);
};

contemplateTranslation(getMessage(), function(translated){
    console.log('Synch Message, Asynch Translate: ' + translated);
});

// what if the message is async?
function getDelayedMessage(cb) {
    setTimeout(function(){
        cb('Hello');
    },1000);
};

getDelayedMessage(function(msg){
   console.log('Asynch Message, Synch Translate', francofy(msg));
});

// what if you need to call an asynchronous API to get your message and then
// call another asynchronous API to translate it?

getDelayedMessage(function(msg){
    contemplateTranslation(msg, function(translated){
        console.log("My God, it's full of callbacks", translated);
    });
});

Note also that there are other ways to deal with asynchronous operations, such as with promises (I prefer the Q promise library myself, but there are other options). However, probably worth understanding the core behavior before you overlay abstractions over it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top