Home Asynchronous translation with Google Translate API. What am I doing wrong?
Reply: 0

Asynchronous translation with Google Translate API. What am I doing wrong?

user1185
1#
user1185 Published in May 20, 2018, 3:38 pm

I always get tangled with asynchronous code, and I don't know where my mistake is.

This code reads product names from a database and puts them in the untranslated array. After that, the array is iterated over, every item is translated, and pushed in a new translated array.

The SQL part works fine, but unfortunately, the translated array is empty. I'm using the mssql and translate npm packages.

How can I make this work?

var untranslated = [];
var translated = [];

var query = `select name from products`

new sql.ConnectionPool(db).connect().then(pool => {
    return pool.request().query(query)
}).then(result => {

    for (var i = 0; i < result.recordset.length; i++) {
        var item = result.recordset[i];

        untranslated.push(item.name)
    }

    // I'm messing it up here somewhere.
    untranslated.map(item => {
        translate(item, { from: 'mk', to: 'en' }).then(result => {
            translated.push(result);
        })
    })

    console.log(translated); // Logs [];

}).catch(err => {
    console.log(err);
    sql.close();
});
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30562 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO