如何使一个 JavaScript 函数在另一个函数完成后运行?

5
我是使用Apache Cordova开发移动应用程序的。问题是我想获取手机号码,然后通过jQuery get函数进行授权发送。所有函数都没问题,但获取手机号码的函数比其他函数慢,并且最后才完成。
我的代码摘要如下:
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");
    });
};

我不知道为什么我先得到了ALERT1,然后才得到ALERT2。我想在收到ALERT2后运行我的其他代码。
任何建议都将不胜感激。

telephoneNumber.get() 是异步的吗? - Satpal
我不知道,那是一个插件: https://gist.github.com/macdonst/4221765 - Salman
2个回答

5
如果telephone.get是异步的,你需要等待它完成后才能进行第一次提示。
document.addEventListener("deviceready", onDeviceReady, false);

请编写 devicePhoneNumber 函数,接受一个回调函数 done。回调函数将会接收两个参数,err(如果存在)和 result。无论 telephoneNumber.get 返回什么,回调函数都将被调用。

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."));
  });
}

现在要使用该函数,请传递一个回调函数,接受两个参数errresult。在回调函数中,检查错误是否存在。如果存在,则进行相应处理。您可以使用err.message访问错误消息。

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

有没有办法将“result”放在本地变量中?类似于: var PhoneNumber = devicePhoneNumber(); - Salman
"result" 是一个本地变量。你是什么意思? - Mulan
var PhoneNumber = devicePhoneNumber(); 变量电话号码等于设备电话号码(); - Salman

1

为您的devicePhoneNumber()函数添加一个callback函数:

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

两个答案都是正确的,对我很有帮助,我不知道哪一个是最好的答案。 - Salman
@northkildonan,不要生气,我只是在考虑未来并编写了一个完全可重用的函数。 - Mulan
@northkildonan,关于“如果他拿了你的代码,他可能甚至不知道自己在做什么”的问题,我已经非常详细地解释了我的解决方案的设计。 - Mulan
@naomik,你解释“设计”也没关系。他甚至不知道回调函数是什么。所以对于第一次使用回调函数,我的例子肯定更好。此外,“向前思考一步”——脚踏实地——你只是给回调函数添加了参数,仅此而已。 - low_rents
2
@naomik 嗨,我实在忍不住要评论一下。感谢 @northkildonan 的论点和阅读评论,我至少在某种程度上理解了“控制反转”的概念。我觉得这些评论至少让我明白了如何去处理异步解决方案。感谢你们两个,@northkildonan 和 @naomik。如果没有 @northkildonan 的论点和 @naomik 提供的解决方案,我很难理解为什么 @naomik 的解决方案是通用的。我会把它当作另一个特定问题的解决方案而忽略它。 - frank
显示剩余8条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接