How to wait for the Javascript callback

1

I have a problem, I know because of how javascript works, but I do not know how to work around it.

I'm using Cordova and a feature needs to use Phone permission on Android.

So before running the method I check if the permission was granted, if I do not ask permission.

The problem is that you do not expect the return and the value always stays undefined.

Follow the code

var getImeiNumeber = function()
{
  if (hasReadPermission() !== true){
    requestReadPermission();

    getImeiNumeber();
  } else if (hasReadPermission() === false) {
    window.plugins.sim.getSimInfo(successCallback, errorCallback);
  }
}

The function

var successCallback = function(result)
{
  console.log(result);

  return result;
}

var errorCallback = function(error)
{
  console.log(error);
}

// Android only: check permission
var hasReadPermission = function()
{
  window.plugins.sim.hasReadPermission(successCallback, errorCallback);
}

// Android only: request permission
var requestReadPermission = function()
{
  window.plugins.sim.requestReadPermission(successCallback, errorCallback);
}
    
asked by anonymous 17.03.2017 / 17:02

1 answer

1

You need to control the flow of these callbacks. A solution would be a pure function (which uses nothing outside itself or its arguments).

It could be this way (jsFiddle):

function getImeiNumeber(succ, err) {
    hasReadPermission(function(res){
        if (res) succ(res);
        else requestReadPermission(succ, err);
    }, err)
}

So she calls hasReadPermission , which gives a result. If the result is positive it calls the callback of the getImeiNumeber arguments with the value received. If it is false call requestReadPermission passing / continuing callback. So regardless of whether you use hasReadPermission or requestReadPermission one of the callbacks will be called.

    
17.03.2017 / 17:54