Skip to content

Instantly share code, notes, and snippets.

@MrRaindrop
Created February 26, 2015 06:59
Show Gist options
  • Save MrRaindrop/3f8e54d2fca433370b8b to your computer and use it in GitHub Desktop.
Save MrRaindrop/3f8e54d2fca433370b8b to your computer and use it in GitHub Desktop.
js: use web notification as a promise.
function notifyMessage(message, options, callback) {
if (Notification && Notification.permission === 'granted') {
var notification = new Notification(message, options);
callback(null, notification);
} else if (Notification.requestPermission) {
Notification.requestPermission(function (status) {
if (Notification.permission !== status) {
Notification.permission = status;
}
if (status === 'granted') {
var notification = new Notification(message, options);
callback(null, notification);
} else {
callback(new Error('user denied'));
}
});
} else {
callback(new Error('doesn\'t support Notification API'));
}
}
function notifyMessageAsPromise(message, options) {
return new Promise(function (resolve, reject) {
notifyMessage(message, options, function (error, notification) {
if (error) {
reject(error);
} else {
resolve(notification);
}
});
});
}
// 运行示例
notifyMessageAsPromise("Hi!").then(function (notification) {
console.log(notification);// 通知对象
}).catch(function(error){
console.error(error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment