从方法返回承诺结果

Return promise result from method

本文关键字:结果 承诺 返回 方法      更新时间:2023-09-26

我正在尝试使用$cordovaLocalNotification插件提供的getAllIds()方法为通知创建一个新的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');
  }
};
})

不确定这是否是正确的方法,但它解决了我的问题。我删除了latestId()方法,并将承诺包装在setNotification()代码周围,以便它在承诺解决之前不会尝试创建通知。见下文:

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()
        });
      });
    });
  }
};