Need help making this translation function work with an array input

181 views Asked by At

I am trying to input an array of string values and translate them using an API then bring them back and display the array in the same order. I have been trying to make this work using the async.map function, however I can not find any resources or examples that help me understand how to properly do this. This is what I have so far,

    var request = require('request');
    var async = require('async');
    var array = ["This", "wedding", "is", "horse shit"]

    var translate = function translate(inText, doneCallback) {
        request({
            method: 'POST',
            url: "https://lc-api.sdl.com/translate",
            headers: {
                 "Content-type": 'application/json',
                  "Accept": 'application/json',
                  "Authorization": 'LC apiKey=api_key_here'
            },
            body: {
                to: 'fra',
                from: 'eng',
                text: inText
            },
            json: true
        }, doneCallback(null, body.translation)));
    }
    async.map(array, translate, function (err, result) {
        if (err) {
            console.log("error");
        } else {
            console.log(result);
        }
    });

Any help in pointing out the proper way to do this, or a better way is much appreciated.

1

There are 1 answers

0
Gábor Imre On BEST ANSWER

I think the error is whithin the translate function, the callback is called instantaneously, you don't wait for the asynchronous answer. Try something like this:

funcion translate(inText, doneCallback) {
    $.get({ /* params */ }, function(response) {
        // Make the external callback only in the callback of the request
        doneCallback(null, response.translation);
    }); 
});