-1

I'm trying to wrap my head around promises and struggling a little bit.

This is the code:

// For Every row.
var prom = new Promise( (resolve, reject) => {

        existing_rows.forEach ((item,index) => {
            console.log("onto index: " + index);
            //We just need to set item[2]! 
            if (item[1].indexOf('%')===-1) {
                //Cool no percentage sign.
                translateClient.translate(item[1], 'th')
                    .then((results) => {
                        const translation = results[0];
                        console.log("translation is: " + translation);
                        item[2] = translation;
                     });
            }
        })

        resolve("Stuff worked!");
    })

prom.then(
    (result) => {
        //Cool that's finished.
        console.log("done!")
        console.log(JSON.stringify(existing_rows));
    }

)

existing_rows is just an array I'm looking at with some stuff to translate using the google api. I want the translations to all be placed in the existing_rows array before I log it in the prom.then block.

At the moment, the output is in this order:

onto index 0
onto index ..
onto index 8

done!
logs the array without the translations

translation is: ...... x 8

Thanks

Kevin B
  • 94,570
  • 16
  • 163
  • 180
James Adams
  • 678
  • 4
  • 11
  • 21
  • 1
    Suggest you use `Promise.all` + `Array#map` instead of `new Promise` + `Array#forEach` – Jaromanda X Feb 15 '17 at 22:15
  • And create a new promise for each 'iteration' within the map? – James Adams Feb 15 '17 at 22:20
  • Ah I'll check out your answer :P – James Adams Feb 15 '17 at 22:20
  • There are a number of questions about this already on the site. See http://stackoverflow.com/q/28134271/215552, http://stackoverflow.com/q/17217736/215552, http://stackoverflow.com/q/31947933/215552... – Heretic Monkey Feb 15 '17 at 22:24
  • @MikeMcCaughan - I agree those questions seem to be similar, the interesting thing is, none of the accepted answers would be usable for this code – Jaromanda X Feb 15 '17 at 22:31
  • I found both of those but couldn't really apply them to my case.. @MikeMcCaughan – James Adams Feb 15 '17 at 22:58
  • @JaromandaX Well, there's more to a duplicate than the accepted answer, but searching on the title came up with http://stackoverflow.com/q/31426740/215552 and http://stackoverflow.com/q/37213783/215552, which are both pretty close. Note that I didn't vote to close as a duplicate, I'm just saying that this question, and questions like it, have been asked many times, and searching first is generally a good idea. – Heretic Monkey Feb 15 '17 at 23:04

2 Answers2

1

Using Promise.all and Array#map instead of new Promise and Array#forEach

var prom = Promise.all(existing_rows.map((item, index) => {
        console.log("onto index: " + index);
        //We just need to set item[2]! 
        if (item[1].indexOf('%') === -1) {
            //Cool no percentage sign.
            return translateClient.translate(item[1], 'th')
                .then((results) => {
                    const translation = results[0];
                    console.log("translation is: " + translation);
                    item[2] = translation;
                });
        }
        // see note 1
    })
);
prom.then(
    (result) => {
        //Cool that's finished.
        console.log("done!")
        console.log(JSON.stringify(existing_rows));
    }
)

[1] there is no return value here, but that's OK, that's the equivalent of return undefined and Promise.all works fine with an array of non-Promises + Promises ...

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

Roughly, like this:

// For Every row.
Promise.all(existing_rows.map((item, index) => {
      console.log("onto index: " + index);
      // We just need to set item[2]! 
      if (item[1].indexOf('%')===-1) {
          // Cool no percentage sign.
          return translateClient.translate(item[1], 'th')
              .then((results) => {
                  const translation = results[0];
                  console.log("translation is: " + translation);
                  item[2] = translation;
              });
      }
}))
.then(result => {
    // Cool that's finished.
    console.log("done!")
    console.log(JSON.stringify(existing_rows));      
})
unional
  • 14,651
  • 5
  • 32
  • 56