Search code examples
reactjstypescriptredux

Async/await not working in a for-of loop defined in createAsyncThunk


I'm having trouble trying to get an async await to work inside a for loop when using createAsyncThunk. I expected that dispatch(performRunAllCells()) will call the API updateBrowser() synchronously for each cell in the editor.cells array in order. Instead, the dispatch resulted in updateBrowser() being called asynchronously all at once. What is happening here?

export const performRunAllCells = createAsyncThunk(
  'editor/runAllCells',
  async (_, { dispatch, getState, rejectWithValue }) => {
    const { notebook: { selectedDataset } } = getState() as {notebook: {selectedDataset: string}};
    const { editor } = getState() as {editor: EditorState};

    try {
      let results: DataEntity | undefined;
      for (const cell of editor.cells) {
        dispatch(setCellStatus({ id: cell.id, execStatus: '*' }));
        results = await updateBrowser(selectedDataset, cell.editorContent);
        dispatch(setCellStatus({ id: cell.id }));
      }
      return results;
    } catch (e) {
      return rejectWithValue(e.response.data);
    }
  },
);

Edit

Currently I'm testing updateBrowser() with a setTimeout:

export async function updateBrowser(selectedDataset: string, editorContent: string): Promise<DataEntity> {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('test');
      resolve({
        raw: editorContent, html: 'Test', console: 'Test',
      });
    }, 3000);
  });
}

I was able to know if it's synchronous/asynchronous through the console log above. Currently, it is printing multiple "test" at once.


Solution

  • Nevermind. I made a mistake somewhere else and the code wasn't actually being called. It is working now after fixing it.