【问题标题】:Why does this async await code not work in this example code? [duplicate]为什么此异步等待代码在此示例代码中不起作用? [复制]
【发布时间】:2021-01-27 03:24:42
【问题描述】:

正在关注 youtube 上的教程,但不幸的是没有用。有人能告诉我哪里出错了吗?

let posts = [
  {name: '1', data: 'Hi1'},
  {name: '2', data: 'Hi2'},
]

function getPosts() {
  setTimeout(()=> {
    posts.forEach((post) => {
      console.log(post.name)

    })
  }, 1000)
}

function createPost(post) {
  setTimeout(()=> {
    posts.push(post)
  }, 2000)
  
} 



async function init() {
  await createPost({name: '3', data: 'hey'})
  getPosts()
}

init();

【问题讨论】:

  • 1. getPostscreatePost 都没有返回承诺,所以 await (基本上)在这里没有效果。 2. setTimeout 也不返回一个承诺,即使你已经返回了它的值,你也不能 await 那。 Unless you convert it to a promise

标签: javascript


【解决方案1】:

您的 createPost 不是异步函数,因此 getPost() 不会等待 createPost 完成,因此它会立即运行。到那时,posts 变量已经没有第三项了。

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2014-12-03
    • 2011-10-25
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多