我目前正在使用 WP-API,我正在从对象中的元素创建页面。我基本上想做的是遍历对象,对于每个元素:创建页面,获取返回的 pageID,将其保存到元素中,然后继续处理对象中的下一个元素。
但是,当前发生的事情是,它不会等待元素完成创建WP页面。
我知道这是一个常见的问题,但我没有找到适合"对于...在...」使用的循环。
这是我的代码 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
返回任何承诺,所以没有什么await
可以等待的。
您已经返回了承诺链创建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;
})
}