Javascript JS异步函数永远在等待

Javascript JS异步函数永远在等待,javascript,async-await,Javascript,Async Await,我读了很多关于AsyncWait的书,但显然我还是不明白- 我正在尝试转换以下内容。然后将promise结构转换为async await: componentDidMount() { const { store } = this.props Promise.all([ API.fetchTodos(), API.fetchGoals(), ]).then(([ todos, goals ]) => { store.dispatc

我读了很多关于AsyncWait的书,但显然我还是不明白-

我正在尝试转换以下内容。然后将promise结构转换为async await:

componentDidMount() {
    const { store } = this.props

    Promise.all([
      API.fetchTodos(),
      API.fetchGoals(),
    ]).then(([ todos, goals ]) => {
      store.dispatch(receiveDataAction(todos, goals))
    })

    store.subscribe(() => this.forceUpdate())

    console.log('test')
}
我的结果是:

async componentDidMount() {
    const { store } = this.props

    const [todos, goals] = await Promise.all([
      API.fetchTodos(),
      API.fetchGoals(),
    ])

    store.dispatch(receiveDataAction(todos, goals))

    store.subscribe(() => this.forceUpdate())

    console.log('test')
}

结果是这个函数永远不会结束。它调用包括console.log在内的所有内容,但程序只是停止,没有错误。我不会向您展示应用程序的任何其他部分,因为根据我的理解,这两个函数应该是等效的,所以其余部分应该无关紧要。显然我错了我做错了什么?为什么我的解决方案不起作用?

在第二个async/await示例中,您在获取目标和TODO之后才订阅存储,而在第一个示例中,您立即订阅

所以你的第二个例子不起作用了,因为现在你已经保证了

store.dispatch(receiveDataAction(todos, goals))
以前打过电话吗

store.subscribe(() => this.forceUpdate())
而且,由于该操作已在该点调度,因此永远不会调用订阅回调

要解决这个问题,您可能只想移动订阅部分,使其在等待调用之前发生。这样,在承诺解决之前,您就已经签署了。比如说:

async componentDidMount() {
    const { store } = this.props

    // Move to the front so this happens before the await.
    store.subscribe(() => this.forceUpdate())

    const [todos, goals] = await Promise.all([
      API.fetchTodos(),
      API.fetchGoals(),
    ])

    store.dispatch(receiveDataAction(todos, goals))

    console.log('test')
}

这两个代码片段之间的区别在于,在第二个async/await示例中,在获取目标和TODO之前,您不会订阅存储,而在第一个示例中,您会立即订阅

所以你的第二个例子不起作用了,因为现在你已经保证了

store.dispatch(receiveDataAction(todos, goals))
以前打过电话吗

store.subscribe(() => this.forceUpdate())
而且,由于该操作已在该点调度,因此永远不会调用订阅回调

要解决这个问题,您可能只想移动订阅部分,使其在等待调用之前发生。这样,在承诺解决之前,您就已经签署了。比如说:

async componentDidMount() {
    const { store } = this.props

    // Move to the front so this happens before the await.
    store.subscribe(() => this.forceUpdate())

    const [todos, goals] = await Promise.all([
      API.fetchTodos(),
      API.fetchGoals(),
    ])

    store.dispatch(receiveDataAction(todos, goals))

    console.log('test')
}

哦,我想我对Wait是如何工作的理解没有错。好的,但是现在让我们假设同步订阅调用需要很长的时间,因此在这种情况下,您可能不想将其移动到顶部,因为您希望立即启动异步获取,然后在等待响应时使用时间来执行繁重的同步操作。在这种情况下,第一个例子正是您想要的,但是如何使用async await?哦,我想我对await如何工作的理解没有错。好的,但是现在让我们假设同步订阅调用需要很长的时间,因此在这种情况下,您可能不想将其移动到顶部,因为您希望立即启动异步获取,然后在等待响应时使用时间来执行繁重的同步操作。在这种情况下,第一个示例正是您想要的,但是如何使用async await?