返回方法的承诺结果

时间:2015-10-24 10:56:19

标签: javascript promise ionic ngcordova

我尝试使用getAllIds()插件提供的$cordovaLocalNotification方法为通知创建新ID。

我有一个notify类,它有一个创建新ID的方法,以及一个用于创建通知的后续方法,如下所示:

var notify = {
  latestId: function() {
      $cordovaLocalNotification.getAllIds().then(function(result){
      return result.length;
    })
  },
  setNotification: function(show) {
    $ionicPlatform.ready(function() {
      $cordovaLocalNotification.schedule({
        id: notify.latestId,
        title: show.name + " is out today!",
      });
    });
  }
};

我尝试使用id: notify.latestId分配结果它似乎是空的承诺对象或其他东西。我尝试了很多不同的设计模式,但我认为我缺少一些基本的东西。任何帮助将不胜感激!

编辑:整个工厂做得很好。

.factory('Notifications', function($cordovaLocalNotification,   $ionicPlatform) {

    var notify = {
  alertTime: function() {
    t = new Date();
    t.setSeconds(t.getSeconds() + 10);
    return t;
  },
  latestId: function() {
    var newId;
    $cordovaLocalNotification.getAllIds().then(function(result){
      console.log('Get all ids: ' + result) //Returned 2nd: 'Get all ids: 1,0,4,5,3,2'
      newId = result.length;
      console.log('New id: ' + newId);//Returned 3rd: 'New id: 6'
    });
    console.log('New id: ' + newId); //Returned first: 'New id: undefined'
    return newId;
  },
  clearAll: function() {
    $cordovaLocalNotification.clearAll();
  },
  setNotification: function(show) {
    $ionicPlatform.ready(function() {
      $cordovaLocalNotification.schedule({
        id: notify.latestId(), // undefined
        title: show.name + " is out today!",
        firstAt: notify.alertTime()
      });
    });
  }
};
return {
  setNotification: function(show){
    notify.setNotification(show);
  },
  clearAll: function(){
    notify.clearAll()
  },
  setAll: function() {
    console.log('Set all');
  }
};
})

1 个答案:

答案 0 :(得分:0)

不确定这是否是正确的方法,但它解决了我的问题。我删除了latestId()方法,并围绕setNotification()代码包装了promise,这样它就不会尝试创建通知,直到promise被解决。见下文:

var notify = {
  alertTime: function() {
    t = new Date();
    t.setSeconds(t.getSeconds() + 10);
    return t;
  },
  clearAll: function() {
    $cordovaLocalNotification.clearAll();
  },
  setNotification: function(show) {
    $ionicPlatform.ready(function() {
      $cordovaLocalNotification.getAllIds().then(function(result){
        var newId = result.length;
        $cordovaLocalNotification.schedule({
          id: newId,
          title: show.name + " is out today!",
          firstAt: notify.alertTime()
        });
      });
    });
  }
};