0

I have a websocket interface which I implemented so that I can use to send requests. The problem is that the response is asynchronous and it initially returns the empty array because retObj is not updated from the callback function that I sent in. How can I make this function so that it will return the populated array when it has been updated. This is how my Service looks like:

import * as interface from '../webSocket'

const carService = () => {
  return {
    getCars: () => {
      interface.sendRequest(function (returnObject) {
       //
      }).then(d => d)
    }
  }
}

export default carService()

And this is how my action looks like:

import { GET_CARS } from '../constants'
import carService from '../carService'

export const getCars = () => async (dispatch) => {
  try {
    const cars = await carService.getCars()
    console.log("At cars actions: ", cars) // logs: Array []
    dispatch(getCarsSuccess(cars))
  } catch (err) {
    console.log('Error: ', err)
  }
}

const getCarsSuccess = (cars) => ({
  type: GET_CARS,
  payload: cars
})
Sachihiro
  • 1,597
  • 2
  • 20
  • 46
  • Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Krzysztof Krzeszewski Jul 05 '21 at 10:47
  • I was looking at this answer for a while, but could not make it to work for me and that is why I posted the question. But forgot to mention that I was looking at this thread. – Sachihiro Jul 05 '21 at 10:48
  • It should work, show us how you tried to implement it – Krzysztof Krzeszewski Jul 05 '21 at 11:00
  • I tried to use then as you can see at the carService function, but then it never arrives at car actions because it never logs "At car actions ..." – Sachihiro Jul 05 '21 at 11:06

2 Answers2

0

You simply have to wrap your callback into promise, since it was not a promise to begin with, which is why you cannot use then or await

import * as interface from '../webSocket'

const carService = () => {
  return {
    getCars: () => {
      return new Promise(resolve => interface.sendRequest(function (returnObject) {
       resolve(returnObject.msg)
      }));
    }
  }
}

export default carService()
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
0

The problem is, you cant await a function unless it returns a Promise. So, as you can guess, the problem lies in carService.getCars's definition. Try this:

getCars: () => {
  return new Promise((resolve, reject) => {
    interface.sendRequest(function(returnObject) {
      // if theres an error, reject(error)
      resolve(returnObject);
    })
  })
}

Or, if sendRequest os am async function, simply return the return value of sendRequest:

getCars: () => {
  return interface.sendRequest()
}
Sagi Rika
  • 2,839
  • 1
  • 12
  • 32