从方法返回承诺结果
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
分配结果,它似乎是空的承诺对象或其他东西。我已经尝试了很多不同的设计模式,但我认为我错过了一些基本的东西。任何帮助将非常感激!
编辑:整个工厂为好措施。
.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()
});
});
});
}
};
相关文章:
- 承诺,如果第一个失败,则返回第二个承诺结果
- 不要在顺序链式承诺中包含 q 承诺结果
- Javascript承诺-检索结果
- JQuery 承诺:访问外部变量或将结果传递给 .done 内部的 IIFE
- 进行多个 http 调用并使用承诺合并结果
- 是否有可能将承诺的结果作为论据传递给 IIFE
- 为什么同步使用承诺会返回异步结果
- 如何返回嵌套承诺的结果
- 如何使用 Parse.promise javascript 定义一个承诺数组并获取结果数组 [parse.com]
- NodeJS 流解析并根据承诺结果逐行写入 json
- 承诺链接:在next-then回调中使用上一个承诺的结果
- 所有的承诺取决于另一个承诺的结果
- 将递归承诺的结果添加到数组中
- RxJS:连接三个承诺,区分结果
- 承诺在以不同方式执行时显示不同的结果
- AngularJS$http结果与承诺
- 在测试我的AngularJS控制器时,我如何模拟$http.get承诺中的结果
- Angular-多次承诺和迭代-如何获得结果
- 承诺分解器/拒绝器能触发相反的结果吗
- 从方法返回承诺结果