Search code examples
reactjsreduxreact-reduxsequelize.jsredux-thunk

Of Redux Thunk, Sequelize (Bluebird) - returning promise to action creator "chain"


So similar to some previous posts referenced below, I'm trying to chain dispatch through Thunk, however my difficulty is on the return from Sequelize. I can see the MySQL query hit the DB and return data, however that return is not flowing through the action-creator to the subsequent .then

I presume it's the manner in which I'm trying to use Sequelize - I'm new to it.

Many thanks!

Code:

initDB.js

...
export function sequelizeQry(qryName: string) {
  let query;

  // For later query mapping
  switch (qryName) {
    case 'POSummary':
      query = qry.spPOLedgerCardSummaryALL;
      break;
    default:
      query = qry.spPOLedgerCardSummaryALL;
  }

  return new sequelize.Promise(
    () => sequelize.query(query, { type: sequelize.QueryTypes.RAW })
      .then((response) => {
        console.log('Returning promise: ', response);        //<-- This hits the console with data
        return response;
      })
  );
}

database-actions.js

// @flow
import { fetchingQuery } from '../action-creators/database-creators';

const fetchQuery = (qryName: string) =>
  (dispatch: *) => dispatch(fetchingQuery(qryName));

export default fetchQuery;

database-creators.js

// @flow
// Action Types
import { FETCH_QUERY } from '../constants/ActionTypes';
import { sequelizeQry } from '../utils/initDB';

/** Action-creators */
export function fetchingQuery(qryName: string) {
  const actionType = FETCH_QUERY;

  return (dispatch: *) => {
    dispatch({ type: `${actionType}_PENDING` });
    sequelizeQry(qryName)                          //<-- This gets called
      .then((payload) => dispatch({                //<-- Don't seem to get here
        type: `${actionType}_FULFILLED`,
        payload
      }))
      .catch(err =>
        // Dispatch the error action with error information
        dispatch({
          type: `${actionType}_REJECTED`,
          error: err
        })
      );
  };
}

Some other references I've checked:

  1. Redux thunk: return promise from dispatched action
  2. return promise from store after redux thunk dispatch

Solution

  • All credit goes to adrice727.

    Here's the code change for future visitors:

    ...
      return new sequelize.Promise(
        () => sequelize.query(query, { type: sequelize.QueryTypes.RAW })
          .then((response) => {
            console.log('Returning promise: ', response);        //<-- This hits the console with data
            return response;
          })
      );
    ...
    
    // BECOMES
    
    return new sequelize.Promise(
        (resolve) => sequelize.query(query, { type: sequelize.QueryTypes.RAW })
          .then((response) => {
            console.log('Returning promise: ', response);
            return resolve(response);
          })
      );