How to make javascript function to run after another?

I am using Apache Cordova to develop a mobile application. the problem is that I want to get a mobile phone number and then send it through the jQuery get function for authorization. all functions are in order, but the function that receives the mobile number is slower than the others, and it ends last.

my code summary is as follows:

document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { devicePhoneNumber(); alert("ALERT1"); // ALERT1 }; function devicePhoneNumber() { var telephoneNumber = cordova.require("telephonenumber"); telephoneNumber.get(function (result) { alert(result); //ALERT2 }, function () { alert("error"); }); }; 

I don't know why first get ALERT1, and after that I get ALERT2. I want to run other codes after receiving ALERT2.

Any suggestion would be appreciated.

+5
source share
2 answers

If telephone.get is asynchronous, you need to wait for it to complete before you can make your first warning.

 document.addEventListener("deviceready", onDeviceReady, false); 

Write a devicePhoneNumber function to accept the done callback. The callback receives two parameters: err (if present) and result . Regardless of telephoneNumber.get , the callback will still be called

 function devicePhoneNumber(done) { var telephoneNumber = cordova.require("telephonenumber"); telephoneNumber.get(function (result) { done(null, result); }, function () { done(Error("There was an error getting the phone number.")); }); } 

To use the function now, pass a callback function that takes two parameters, err and result . Check for an error in your callback. If present, treat it accordingly. You may receive an error using err.message .

 function onDeviceReady() { devicePhoneNumber(function(err, result) { if (err) return alert(err.message); alert("Alert 1"); // alert 1 alert(result); // alert 2 }); } 
+5
source

add the callback function to your devicePhoneNumber() function:

 document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { devicePhoneNumber(function(){ //anonymous function for the callback parameter /* everything you put in here will be executed only AFTER telephoneNumber.get() has run successfully */ alert("ALERT1"); // ALERT1 }); }; function devicePhoneNumber(callback) { var telephoneNumber = cordova.require("telephonenumber"); telephoneNumber.get(function (result) { alert(result); //ALERT2 callback(); //callback function is called here }, function () { alert("error"); }); }; 
+1
source

Source: https://habr.com/ru/post/1202401/


All Articles