2017-02-21 3 views
1

Почему следующий код регистрирует массив ожидающих обещаний? Я ожидаю, что все обещания в массиве будут решены, а затем выполните функции внутри методов .then.. Then Выполняется на «ожидании» вместо разрешения Разрешено

for (let i = 0; i < limit; i++) { 
    promiseArray.push(fetch(someUrls[i])) 
} 

Promise.all(promiseArray) 
    .then(responses => responses.map(response => response.text())) 
    .then(result => console.log(result)) 

Заранее спасибо

ответ

6

Это потому, что response.text() method returns a promise. fetch - вещь с двумя обещаниями. Один - для фактического запроса, а другой для преобразования.

Что вы можете сделать, это обернуть операцию array.map в другую Promise.all.

Promise.all(promiseArray) 
    .then(responses => Promise.all(responses.map(response => response.text()))) 
    .then(result => console.log(result)) 
2

Вам нужно положить прикованным то внутри Promise.all тоже как response.text() также возвращает другое обещание.

for (let i = 0; i < limit; i++) { 
    promiseArray.push(fetch(someUrls[i])) 
} 

Promise.all(promiseArray) 
    .then(responses => Promise.all(responses.map(response => response.text()))) //Needs to wait for all text() promise methods to resolve 
    .then(result => console.log(result)) 

или вы можете Обещания цепи в вашей цикл:

for (let i = 0; i < limit; i++) { 
    promiseArray.push(fetch(someUrls[i]).then(res => res.text())); 
} 

Promise.all(promiseArray).then(result => console.log(result)) 
Смежные вопросы