繁体   English   中英

从方法返回承诺结果

[英]Return promise result from method

我正在尝试使用$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分配结果id: notify.latestId似乎是空的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()方法,并将promise包裹在setNotification()代码周围,以便在解决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()
        });
      });
    });
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM