Answer the question
In order to leave comments, you need to log in
How to add a value to an array if it needs to be received by a promise or a delay?
results = results.slice(0, 1);
for (const key in results) {
if (results.hasOwnProperty(key)) {
const element = results[key];
element.introtext = h2p(element.introtext);
element.fulltext = h2p(element.fulltext);
clientGI.search(element.title)
.then(images => {
element.images = images.map(image => [image.url, image.thumbnail]);
});
}
}
Answer the question
In order to leave comments, you need to log in
const waitLoad = [];
results = results.slice(0, 1);
for (const key in results) {
if (results.hasOwnProperty(key)) {
const element = results[key];
element.introtext = h2p(element.introtext);
element.fulltext = h2p(element.fulltext);
// добавим промис полученный в
waitLoad.push(
clientGI.search(element.title)
.then(images => {
element.images = images.map(image => [image.url, image.thumbnail]);
// возвращаем промис который всегда выполнится
return Promise.resolve(element);
});
);
}
}
// когда все картинки загружены выполняем какие либо действия с ними
Promise.all(waitLoad).then(values => {
// ...
});
Something like this:
function getWithImages(result) {
return new Promise((res, rej) => {
const elPromises = [];
for (let key in result) {
if (!result.hasOwnProperty(key)) continue;
const element = result[key];
element.introtext = h2p(element.introtext);
element.fulltext = h2p(element.fulltext);
elPromises.push(
clientGI.search(element.title)
.then(images => {
element.images = images.map(image => [image.url, image.thumbnail]);
});
);
}
Promise.all(elPromises).then(function() {
// все готовы
res(result);
});
});
}
const gotImagesPromise = getWithImages(results[0]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question