drake035
drake035

Reputation: 2877

Getting error with a non-promise function inside a promise chain

In third-party made codebase I found this promise chain:

const signUp = ({ dispatch, commit, getters }, payload) => {
  return dispatch('startTask', { id: signUpRequestTaskId }, { root: true })
    .then(() => enrichSignUpPayload(payload, getters))
    .then(apiRequest.signUpB2b);
};

For solving a certain issue in the app, I need to remove the first link of the chain (dispatch('startTask',...root: true })):

const signUp = ({ dispatch, commit, getters }, payload) => {
  return enrichSignUpPayload(payload, getters)
    .then(apiRequest.signUpB2b);
};

However this triggers the following error:

enrichSignUpPayload(...).then is not a function

Why? There was no error before I remove the first link so why the second link becomes a problem now? I don't get it.

Here's the body of the enrichSignUpPayload() function just in case:

const enrichSignUpPayload = payload => pipe(
  payload,
  (p) => ({ ...p, fromApp: isFromApp() }),
  aperoFromStorage
);

Upvotes: 0

Views: 71

Answers (3)

Ben Aston
Ben Aston

Reputation: 55729

enrichSignUpPayload is not returning a promise.

You can wrap the result using Promise.resolve:

const signUp = ({ dispatch, commit, getters }, payload) =>
    Promise.resolve(enrichSignUpPayload(payload, getters))
        .then(apiRequest.signUpB2b)

Upvotes: 0

n1stre
n1stre

Reputation: 6086

You're getting this error because enrichSignUpPayload does not return a promise as dispatch does. Also, the first version of signUp works because a call to promise.then also returns a promise, so that we can call the next .then on it. Refer to this for more info about it.

I assume, to make things work you could do something like:

const enrichSignUpPayload = payload => pipe(
  payload,
  (p) => ({ ...p, fromApp: isFromApp() }),
  aperoFromStorage,
  (possibleValueFromAperoFromStorage) => Promise.resolve(possibleValueFromAperoFromStorage)
);

Or if the enrichSignUpPayload is not async you can just simply do:

const signUp = ({ dispatch, commit, getters }, payload) => {
  const result = enrichSignUpPayload(payload, getters);
  return apiRequest.signUpB2b(result)
};

Upvotes: 1

Jay
Jay

Reputation: 3107

Did you try adding a function to return

const signUp = ({ dispatch, commit, getters }, payload) => {
  return () => enrichSignUpPayload(payload, getters) // Here add function
    .then(apiRequest.signUpB2b);
};

Upvotes: 0

Related Questions