TransWikia.com

Jquery promises in loop

Stack Overflow Asked by Alan A on December 9, 2021

I am trying to call a function 3 times which injects some mark-up provided by an ad network to my articles. I am trying to implement with promises and a for loop as follows:

var targetParagraph = x;
var slots = {
     8 : '<div>some content</div>',
     9 : '<div>some content</div>',
     10 : '<div>some content</div>'
};

 Object.keys(slots).forEach(function(key) {
      let scriptMarkup = '<div id="snack_dex' + key + '"></div>' + slots[key];
      injectArticleContent(targetParagraph, scriptMarkup).done(function() {
           console.log('done!');
      });
 });

 function injectArticleContent(targetParagraph, scriptMarkup){
      return $( ".js-article-body p:nth-child(" + targetParagraph + ")").after(scriptMarkup);
 }

When I run the above I get the following error:

Uncaught TypeError: injectArticleContent(…).done is not a function

Why is injectArticleContent not a function? I have been looking at past solutions for ours but just cannot figure this out, any ideas?

One Answer

Assuming that getting markup is an async task, you can create a list of promises an resolve them with Promise.all()

let getMarkup = (id) => new Promise((resolve, reject) => {
  setTimeout(function() {
    resolve("markup from server")
  }, 1000)
})

var targetParagraph = 'x';
var slots = {
  8: '<div>some content</div>',
  9: '<div>some content</div>',
  10: '<div>some content</div>'
};

let promisses = Object.keys(slots)
  .map(k => getMarkup(k).then(res => injectArticleContent(k, res)))

Promise.all(promisses)

function injectArticleContent(targetParagraph, scriptMarkup) {
  console.log('rendering new post:: ', targetParagraph, scriptMarkup)
  return $(".js-article-body p:nth-child(" + targetParagraph + ")").after(scriptMarkup);
}

Answered by Jacek Rojek on December 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP