Trying to use deffer on chained functions

I have a list that I would like it to go through a function and make some fixes on that list, so I can use it later.

Because its function is depended on the result of the previous, I decided to use the chained defer, to wait one another.

 $scope.list = function(scan_result){

    var defer = $q.defer();

    defer.promise
      .then(function(){
      // Creates an object list with bssid and signal
        const ap_list = scan_result.map(str => {
        return {
          bssid: str.match(/BSSID:\s(\S*)/)[1],
          signal: str.match(/Signal:\s(\S*)/)[1]
          }
        });
        return ap_list;
      })

      .then(function(ap_list) {
        //Removes the elements that have signal bellow -50
        for (var i=0; i<ap_list.length; i++) {
          if (ap_list[i].signal < -50){
            ap_list.splice(i, 1);
          }
        }
        return ap_list;
      })

      .then(function(ap_list) {
        //Sort the elements Highest to Lowest Signal Level
        ap_list.sort(function(a,b) {
          return a.signal - b.signal;
       });
        return ap_list;
      })
      
      .then(function(ap_list) {
        //From the list keep the highest 3
        return ap_list.slice(0,2);
      })

    return defer.promise;
  }

When I output the result of the $scope.list() function on the console, it says the promise is pending and the status equals to 0.

So, defenetly something is wrong here. Im not a deffer guru so I kindly ask for your help.

Defer delays that function until the promise gets resolved. Usually this is used for when making an Ajax request, so that the script can wait for however long it takes for a response to come back.

As you don’t seem to have any such delays in your code, I recommend that you go ahead without the defer.
Just name each function, and call them, Keep it simple.

function createApList(scan_result) {
    // Creates an object list with bssid and signal
    ...
}
function removeLowSignal(ap_list) {
    //Removes the elements that have signal bellow -50
   ...
}
function sortApList(ap_list) {
    //Sort the elements Highest to Lowest Signal Level
    ...
}
function keepTopThree(ap_list) {
    //From the list keep the highest 3
    ...
}

const apList = removeLowSignal((createApList(scan_result));
const bestApList = keepTopThree(sortApList(apList));
2 Likes

Just to add to @Paul_Wilkins’ reply, you can actually chain those Array methods directly, like

const app_list = scan_data
  .map(str => {
    return {
      bssid: str.match(/BSSID:\s(\S*)/)[1],
      signal: str.match(/Signal:\s(\S*)/)[1]
    }
  })
  .filter(el => el.signal >= -50)
  .sort((a, b) => a.signal - b.signal)
  .slice(0, 2)

I suppose the only thing that might need to get deferred is the obtaining of the scan results itself.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.