简体   繁体   English

Javascript:在“ for .. in”循环中等待对象不等待异步

[英]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. 我目前正在使用WP-API,在其中我根据对象中的元素创建页面。 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. 我基本上想要做的是遍历对象,并为每个元素:创建页面,获取返回的pageID,将其保存到该元素,然后继续该对象中的下一个元素。

However, what's currently happening is that it does not wait for the element to be finished creating the WP page. 但是,当前正在发生的事情是它不会等待元素完成创建WP页面的过程。

I know this is a common question but I did not find an answer suitable to the 'for ... in ...' loop used. 我知道这是一个常见问题,但是我没有找到适合所用“ for ... in ...”循环的答案。

That's my code rn: 那是我的代码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? 我没有正确使用“等待”吗?

You don't return any Promise from createPage so there is nothing await can wait for. 您不会从createPage返回任何Promise,因此没有await等待的地方。

You have return the Promise chain create with wp.pages().create : 您已经通过wp.pages().create返回了Promise链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;
    })
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM