延期承诺无效

时间:2016-09-02 11:43:10

标签: angularjs promise

我正在使用角度来承诺我的网络应用程序 -

var deferred = $q.defer();

成功 -

deferred.resolve(profile); // profile = JSON object

失败 -

deferred.reject(1); // 1 or no value returned

功能结束时 -

return deferred.promise;

然后我正在处理这个返回的Promise对象以调用另一个方法。但是它没有调用。如果我使用Callback(错误,成功)它可以正常工作。可以有人建议我的承诺有什么问题。

代码段 -

  function open() {    // for initializing DB,getting called from service
    var deferred = $q.defer();
    var options = {
      Encryption: {
        encryptKey: false,   // optional encrypt primary key
        secrets: [{
            name: 'dddd',
            key: 'xxxxxxxxxx'
        }]
      }
    };

    var schema = {
      stores:[{
        name:'profile',
        encrypted: true
      }]
    };

    var db = new ydn.db.Storage('nowconferdb', schema, options);

    db.onReady(function() {
        console.log('DB is initialized'); // getting this 
        profilestorage.setDB(db); // getting called and setting DB in profilestorage service
        deferred.resolve(true);
    });

    db.addEventListener('fail', function (event) {
        var err = event.getError();
        if (err.name == 'versionchange') {
            console.log('The application is updated, please refresh to upgrade.');
            profilestorage.setup(db);
        } else {
            console.log('connection failed with ' + err.name + ' by ' + err.message);
            db = null; // no operation can be placed to the database instance
        }

        deferred.reject(false);
    });

    return deferred.promise; 
}

这是我的调用方法 -

storageservice.open().then(function() {
  console.log('post initializing storageservice'); // not getting it.
});

非常感谢您的真诚努力。

1 个答案:

答案 0 :(得分:2)

你应该做的是在promise的成功回调中调用你的函数。假设您将承诺分配给deferred变量:

deferred.then(
    function (data) {
        // Here you call your other function/method
        // It will be called when 'deferred' promise is resolved
        anotherFunction();
    },

    function (error) {
        // Handle the error
    }
);

我希望这会有所帮助,即使您提供的信息不够。