0
\$\begingroup\$

My program translates words from one language to another using a language Pivot and systran.io API.

I used promises, callbacks and external API for the first time but I'm not sure that's the best way to use them. The function Translate will translate word and send a response via a callback. Then in the POST request, I used promises to chain tasks.

var express = require('express');
var request = require('request');

var router = express.Router();

router.post("/", function(req, res) {
    console.log
    var resultat
    var promise = new Promise((resolve, reject) => {
        translate(req.query.source, "en", req.query.content, function(resa) {
            resolve(resa);

        })
    }).then(function(resolve) {
        console.log(resolve);
        translate("en", req.query.target, resolve, function(resa2) {
            console.log(resa2);

        })
    });
});

function translate(source, target, content, callback) {
    let result;
    result = request("https://api-platform.systran.net/translation/text/translate?input=" + content + "&source=" + source + "&target=" + target + "&key=xxxxxxxx-783f-4f90-aea4-7fb357016647", function(err, data, body) {
        body = JSON.parse(body);
        console.log(body);

        callback(body.outputs[0].output)
    })
}
module.exports = router;

Is there a better way to write my program, which is already working?

\$\endgroup\$
1
\$\begingroup\$

Personally, I would have the translate call return a Promise rather than a callback and make use of async/await (presuming the version of Node you are using Node 6+) e.g.

var express = require('express');
var request = require('request');

var router = express.Router();

router.post("/", async (req, res, next) => {
  try {
    const translated = await translate(req.query.source, 'en', req.query.content);
    const result = await translate('en', req.query.target, translated); 
    // presume you intend on returning something from your API?
    return res.json({ result });
  } catch (e) {
    return next(e);
  }
})

const translate = (source, target, content) => 
  new Promise((resolve, reject) => 
    request(`https://api-platform.systran.net/translation/text/translate?input=${content}&source=${source}&target=${target}&key=xxxxxxxx-783f-4f90-aea4-7fb357016647`, (err, data, body) => {
      if (err) return reject(err);

      try {
        return resolve(JSON.parse(body));
      } catch (e) {
        return reject(e);
      }
    })
  );

module.exports = router;
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.