如何在函数中放置异步函数?

时间:2017-07-07 10:29:14

标签: javascript node.js asynchronous

这是我正在使用的代码。它不起作用,因为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());

2 个答案:

答案 0 :(得分:1)

您只需将回调函数传递给getAllPosts

getAllPosts(cb){
return client
    .getPosts( {type: 'post', status : 'publish', number : 222} , ['title','id'] , (error, posts) => {
    cb(posts
        .map((item) => {
        return item.title
        }))
    })
}

getAllPosts(function(posts){
   console.log(posts)
})

答案 1 :(得分:0)

在.getPosts()方法中,你使用3个参数,一个对象,一个数组和一个函数referance。

关键是你要向该职能发送一份资料。您应该在流程结束后执行该功能。但是你的代码行不会等到你的流程结束。

相关问题