2017-02-15 1 views
-1

Я пытаюсь обвести голову обеими обещаниями и немного потрудиться.Как сделать обещание подождать до конца цикла

Это код:

// 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 это просто массив я смотрю с некоторыми вещами, чтобы перевести с помощью Google API. Я хочу, чтобы все переводы были помещены в массив existing_rows, прежде чем я запишу его в блок prom.then.

На данный момент выход в следующем порядке:

onto index 0 
onto index .. 
onto index 8 

done! 
logs the array without the translations 

translation is: ...... x 8 

Благодаря

+1

Предлагаем вам использовать 'Promise.all' +' Array # map' вместо 'new Promise' +' Array # forEach' –

+0

И создать новое обещание для каждой «итерации» на карте? –

+0

А я проверю ваш ответ: P –

ответ

1

Использование Promise.all и массива # карта вместо нового Обещание и массив # для каждого

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] здесь нет возвратного значения, но это нормально, это эквивалент return undefined, а Promise.all отлично работает с массивом не обещающих + обещаний ...

0

Грубо говоря, как это:

// 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));  
}) 
+0

Спасибо за ответ, но Яроманда прокомментировал сначала предложение того же самого. –

Смежные вопросы