[英]Javascript: Await in 'for .. in' loop for object not waiting for async
我目前正在使用WP-API,在其中我根据对象中的元素创建页面。 我基本上想要做的是遍历对象,并为每个元素:创建页面,获取返回的pageID,将其保存到该元素,然后继续该对象中的下一个元素。
但是,当前正在发生的事情是它不会等待元素完成创建WP页面的过程。
我知道这是一个常见问题,但是我没有找到适合所用“ for ... in ...”循环的答案。
那是我的代码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;
})
}
谁能告诉我我在做什么错? 我没有正确使用“等待”吗?
您不会从createPage
返回任何Promise,因此没有await
等待的地方。
您已经通过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.