Created
February 26, 2015 06:59
-
-
Save MrRaindrop/3f8e54d2fca433370b8b to your computer and use it in GitHub Desktop.
js: use web notification as a promise.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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