[英]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.