Promise create custom fail is not a function Angularjs error?

依然范特西╮ 提交于 2019-12-24 13:26: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");
    });
};


来源:https://stackoverflow.com/questions/36383275/promise-create-custom-fail-is-not-a-function-angularjs-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!