【发布时间】:2017-07-07 19:16:16
【问题描述】:
这是我正在使用的代码。它不起作用,因为 client.getPosts 是异步的。所以我的问题是,我怎样才能让它工作? client.getPosts 来自 wordpress npm 模块,所以我无法更改它。
// FUNCTIONS
function getAllPosts() {
return client
.getPosts( {type: 'post', status : 'publish', number : 222} , ['title','id'] , (error, posts) => {
return posts
.map((item) => {
return item.title
})
})
}
// MAIN
console.log(getAllPosts());
【问题讨论】:
-
我建议你使用lamba函数,这样你就可以做到:somFunction = () => client.getPost(config) 然后在调用函数时使用promise
-
@arracso 你能以任何方式写给我我需要写的东西吗?我一直在尝试理解 Promise,但仍然不明白如何使用它们,尤其是在我使用模块的情况下。
-
promises 只是一个以另一个函数的结果执行的函数。我不知道 getPosts 是如何工作的,但是如果它像 ajax 请求一样工作,那么您可以在 ajax 中使用 promise,而不是将函数传递给 getPosts:
$.ajax(/*config*/).done(/*here do whatever you whant woth the response*/)´ or you can use other promises like.fail(),.then()@987654325 @.error()`.. 所以最好的选择是使用他的 getPost 配置的功能并像我一样命名它。然后你可以使用带有 promise 的函数。 (我不能更好地解释我的新承诺)
标签: javascript node.js asynchronous