L
L
lex2018-11-04 10:59:50
JavaScript
lex, 2018-11-04 10:59:50

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]);
        });
    }
  }

Good afternoon! How can I wait for my pictures and then update the field in the array and pass this array as resolve ? Please help with advice!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
lex, 2018-11-04
bem @bemdev

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 => { 
// ...
});

S
Sergey Sokolov, 2018-11-04
@sergiks

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 question

Ask a Question

731 491 924 answers to any question