How to wait for Javascript callback

Asked

Viewed 244 times

1

I have a problem, I know because of how javascript works, but I do not know how to solve the problem.

I’m using Cordova and a function need to use the Phone permission on Android.

So before executing the method I check if permission has been granted, if I do not ask permission.

the problem is that it does not wait for the return and the value always stays as Undefined.

Follows 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);
}

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 like this (jsFiddle):

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.