Javascript 从方法返回承诺结果
我正在尝试使用Javascript 从方法返回承诺结果,javascript,promise,ionic,ngcordova,Javascript,Promise,Ionic,Ngcordova,我正在尝试使用$cordovalolocalnotification插件提供的getAllIds()方法为通知创建一个新Id 我有一个notify类,它有一个创建新Id的方法和一个创建通知的后续方法,如下所示: var notify = { latestId: function() { $cordovaLocalNotification.getAllIds().then(function(result){ return result.length; })
$cordovalolocalnotification
插件提供的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
分配结果时,它似乎是一个空的promise对象或其他东西。我尝试了大量不同的设计模式,但我认为我遗漏了一些基本的东西。任何帮助都将不胜感激
编辑:整个工厂的良好措施
.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()
});
});
});
}
};
latestId
是返回承诺的函数,您可能需要id:notify.latestId(),
@Grundy作为问题删除,并根据您的要求作为注释添加;-)“我认为需要包括括号来调用实际函数latestId()…”就像格伦迪说的;)这有意义吗?“notify.alertTime()”是否有有效值?您是否也可以提供结果的输出?如果您只需从latestId
function:-)返回任何内容,请更改为latestId:function(){return$cordovlocalnotification…
并且所有操作都应该有效,不要忘记本地化变量…var t=new Date();