0

i am trying to return a list from redis within a callback function but something i am doing is not right, here is the following function:

public get = () =>
    CoreHelpers.controller("get.alerts", async() => {
      let returnVal: [] = []

      rangeReturn(function(obj:any){
        returnVal = obj.map((x:any) => JSON.parse(x))
        console.log(returnVal) <--- works here
      }, returnVal)

      //Returns the list of the given ticker
      function rangeReturn(callback: any, returnVal: any) {
        RedisClients.client0.lrange("alerts", 0, -1, (err, reply) => {
          if (!err) {
            callback(reply, returnVal);
          } else {
            console.log("Error within client.lrange in Quandl.js");
          }
        });
      }

      console.log(returnVal) <--- doesnt work here
      return returnVal
      
    });

It seems even though i declare the returnVal outside of the function call and pass in the data it is not returning. Im assuming because rangeReturn is not finishing before it is parsing the data? But how do i go about properly formatting it to do so? Thank you!

Lane Floyd
  • 73
  • 1
  • 7

1 Answers1

0

This is where you'd use the Promise constructor with the resolve/reject callbacks:

CoreHelpers.controller("get.alerts", async () => {

    const promise = new Promise((resolve, reject) => {
        RedisClients.client0.lrange("alerts", 0, -1, (err, reply) => {
            if (!err) {
                resolve(reply);
            } else {
                reject(err);
            }
        });
    });

    return promise.then(value => {
        // If you want to modify the value first
        return value.map((x: any) => JSON.parse(x));
    });
});
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31