threxx
threxx

Reputation: 1243

Javascript: Await in 'for .. in' loop for object not waiting for async

I am currently working with the WP-API where I am creating pages from elements in my object. What I basically want to do is to iterate over the object, and for each element: create the page, get the pageID returned, save it to the element and proceed with the next element in the object.

However, what's currently happening is that it does not wait for the element to be finished creating the WP page.

I know this is a common question but I did not find an answer suitable to the 'for ... in ...' loop used.

That's my code rn:

async function checkContent(content) {
    let currentObj;
    for(const key in content) {
        currentObj = content[key][0];
        console.log(currentObj);
        currentObj.postId = await createPage(currentObj.title, currentObj.content);

    }
}


function createPage(title, content) {
    var wp = new WPAPI({
        endpoint: 'http://localhost:8888/wordpress/wp-json',
        username: 'admin',
        password: 'pass'
    });
    wp.pages().create({
        title: title,
        content: content,
        status: 'publish'
    })
        .catch(error => {
            console.error('Error: ' + error.message);
        })
        .then(function (response) {
        console.log(response.id);
        return response.id;
    })
}

Can anyone tell me what I am doing wrong? Am I not using 'await' correctly?

Upvotes: 0

Views: 535

Answers (1)

t.niese
t.niese

Reputation: 40842

You don't return any Promise from createPage so there is nothing await can wait for.

You have return the Promise chain create with wp.pages().create:

function createPage(title, content) {
  var wp = new WPAPI({
    endpoint: 'http://localhost:8888/wordpress/wp-json',
    username: 'admin',
    password: 'pass'
  });

  return wp.pages().create({
      title: title,
      content: content,
      status: 'publish'
    })
    .catch(error => {
      console.error('Error: ' + error.message);
    })
    .then(function(response) {
      console.log(response.id);
      return response.id;
    })
}

Upvotes: 2

Related Questions