Promise create custom fail is not a function Angul

2019-07-26 11:32发布

问题:

As i am trying to use promise to create html5 directory functions in angularjs. but it shows error as promise not defined.

Angular file:-

$scope.createDirectory = function(dirName,dirLocation){
        fileManager.createDirectory(dirName,dirLocation)
        .then(function(data){
            console.log(data, "dir created");
        }).fail(function(err){
            console.log(err,"dir err while creating");
        });
    };

JS File:-

var fileManager = {
createDirectory: function(directoryName,dirLocation){
                    var makePromise = new Promise(function(resolve, reject){
                        dirLocation.getDirectory(directoryName, {create: true, exclusive: false}, function(data){
                            resolve(data);
                        }, function(error){
                            reject(error);
                        });
                    });
                    return makePromise;
                }
}

TypeError: fileManager.createDirectory(...).then(...).fail is not a function
at h.$scope.createDirectory (app.js:60)
at angular.min.js:196
at f (angular.min.js:224)
at h.$eval (angular.min.js:123)
at h.$apply (angular.min.js:123)
at HTMLButtonElement.<anonymous> (angular.min.js:224)
at HTMLButtonElement.c (angular.min.js:32)

how to create promise properly and bind it to angular function. I've used catch instead of fail it worked. how to create custom error callback to all fail function like this

回答1:

There is typo in promise, It should be new Promise. Though I would suggest you to use $q instead of Promise.

The advantage of using $q instead of Promise object is, you code will be angular context & you don't need to care to run digest cycle manually. Where as if you use Promise then you need to run digest cycle manually(as Promise would be native asynchronous JS function, considered to be outside world of angular).

createDirectory: function(directoryName, dirLocation) {
    var makePromise = $q(function(resolve, reject) {
        dirLocation.getDirectory(directoryName, {
            create: true,
            exclusive: false
        }, function(data) {
            resolve(data);
        }, function(error) {
            reject(error);
        });
    });
    return makePromise;
};

Update

.fail function isn't available on $q object, you need to change your fileManager.createDirectory function code call to below.

$scope.createDirectory = function(dirName,dirLocation){
    fileManager.createDirectory(dirName,dirLocation)
    .then(function(data){ //success callback
        console.log(data, "dir created");
    }, function(err){ //error callback
        console.log(err,"dir err while creating");
    });
};