如何在AngularJS承诺中使用回调设计的函数?

Mar*_*hee 0 angularjs angularjs-scope ngcordova

如果Javascript函数设计有回调,那么如何在AngularJS promise中封装该函数?

例如,我在看使用以下科尔多瓦插件:cordova.plugins.diagnostic(见https://www.npmjs.com/package/cordova.plugins.diagnostic).它的许多功能都设计有回调功能.因为请求正在使用设备的操作系统,所以在函数完成之前可能需要一些时间,因此我正在考虑是否应该在promise结构中调用它们.例如,如何转换以下内容:

cordova.plugins.diagnostic.isWifiEnabled(function(enabled){
    <do something>
}, function(error){
    <do something>
});
Run Code Online (Sandbox Code Playgroud)

或者实际上任何通用的回调结构......

masterFunction(function(enabled){
    <do something>
}, function(error){
    <do something>
});
Run Code Online (Sandbox Code Playgroud)

在AngularJS承诺中运作?它会是这样的吗?

function callMasterFunction() {
    var deferred = $q.defer();

    masterFunction(function(enabled){
        <do something>
        deferred.resolve(enabled);
    }, function(error){
        <do something>
        deferred.resolve(error);
    });

    return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)

我认为当使用AngularJS和Cordova以及W3C Geolocation API时,这也是一个问题.在我看来,我可能没有清楚地了解在这些情况下如何管理范围.

最终,我可以看到将这些类型的呼叫链接在一起.就像是:

var promise = callMasterFunction1()
.then(function(response) { return callMasterFunction2(); })
.then(function(response) { return callMasterFunction3(); })
...
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.感谢您的时间.

JLR*_*she 5

您可以使用promise构造函数从基于回调的API创建承诺:

function callMasterFunction() {
    return $q(function (resolve, reject) {
        cordova.plugins.diagnostic.isWifiEnabled(resolve, reject);
    });
}
Run Code Online (Sandbox Code Playgroud)

现在callMasterFunction()返回一个承诺:

callMasterFunction()
    .then(function (enabled) {
        console.log('Wifi is ' + (enabled ? '' : 'not ') + 'enabled.');
    })
    .catch(function (error) {
        console.error('Something went wrong: ', error);
    });
Run Code Online (Sandbox Code Playgroud)

当你想链接它们时,你可以这样做:

var promise = callMasterFunction1()
    .then(callMasterFunction2)
    .then(callMasterFunction3);
Run Code Online (Sandbox Code Playgroud)