如何在Javascript中的forEach循环中使用异步

如何在Javascript中的forEach循环中使用异步

本文介绍了如何在Javascript中的forEach循环中使用异步/等待语法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经研究了关于通过forEach循环使用async/await的几个问题,但似乎没有什么能解决我的用户情况...如何才能使下面的代码正常工作?现在,我收到以下错误:

I've looked at several questions on using async/await with a forEach loop but nothing seems to cover my user case... How can I get the code below to work? Right now I'm getting the following error:

这是代码:

export const fetchUserBookmarks = ( bookmarksIDs ) => async ( dispatch, getState, api ) => {

    dispatch({
        type: 'IS_FETCHING_BOOKMARKS'
    });

    try {

        bookmarks = [];

        bookmarksIDs.forEach( bookmarkID => {
            const bookmark = await api.get( selectedPostByIdEP + bookmarkID );
            bookmarks.push( bookmark );
        });

        dispatch({
            type: 'HAS_FETCHED_BOOKMARKS',
            payload: bookmarks
        });

    } catch( error ) {

        dispatch({
            type: 'FAILED_FETCHING_BOOKMARKS',
            payload: error
        });

    }

}

推荐答案

首先,要使用await,应将函数声明为async.您是通过外部函数完成的,而不是内部函数完成的.

First, To use await you should declare the function as async. You have done so with the outer function but not with the inner function.

更改将如下所示:

bookmarksIDs.forEach(async bookmarkID => {

第二,,您可能想要并行运行这些api调用.

Second, what you probably want is to run those api calls in parallel.

您可以将forEach替换为map调用,然后等待所有产生的诺言.

You can replace forEach with a map call and await all the resulting promises together.

为此,您的代码应如下所示:

To do that your code should look something like this:

const bookmarks = await Promise.all(
  bookmarksIDs.map(bookmarkID =>
    api.get( selectedPostByIdEP + bookmarkID )
  )
);

-

如果在其他任何地方未声明bookmarks,似乎会导致问题.使用constlet应该可以解决该问题.

It seems that if bookmarks is not declared anywhere else it causes a problem. using const or let should solve that problem.

这篇关于如何在Javascript中的forEach循环中使用异步/等待语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:10