【问题标题】:How can I put an async function inside a function?如何将异步函数放入函数中?
【发布时间】: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


【解决方案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)
})

【讨论】:

  • 谢谢,这行得通。不过我真的不明白。事情发生的顺序是什么?
  • 不客气。当您调用getAllPosts 时,它会调用异步getPosts 函数,当结果来自服务器时,getPosts 的回调函数会触发:.getPosts({something}, (err, posts)=>{}) (err, posts)=>{}.getPosts 的回调函数,其中我们将调用我们的回调函数cb 并将结果传递给它。为了更好地理解,请阅读此link
【解决方案2】:

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

关键是您要发送对该函数的引用。您应该在流程结束后执行该功能。但是您的代码行不会等待您的进程结束。

【讨论】:

  • 我返回client.getPosts,这和执行不一样吗?
  • 当您在更高的函数中返回您的值时,您的进程仍在运行。没有什么可退货的。
  • 不要考虑单一时间线。如果您创建进程,则 javascript 中有多个时间线
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-09
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 2020-12-20
  • 1970-01-01
相关资源
最近更新 更多