I am looking for a way to create deferred object which will be resolved outside the current scope. I like deferred objects and as I see Promise.defer()
in Chrome 38 returns the deferred object.
But in latest Firefox 34 Promise.defer
is undefined as well in Safari 8.0.
So I can't use Promise.defer
everywhere now. What about future status? Will it be implemented in other browsers or will be removed as deprecated?
The deferred. promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request.
Simply put you can use $q. defer() to create a Promise. A Promise is a function that returns a single value or error in the future. So whenever you have some asynchronous process that should return a value or an error, you can use $q. defer() to create a new Promise.
Promises are a way to implement asynchronous programming in JavaScript(ES6 which is also known as ECMAScript-6). A Promise acts as a container for future values. Like if you order any food from any site to deliver it to your place that order record will be the promise and the food will be the value of that promise.
Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.
Although I doubt this is a good idea, but technically you can implement custom deferred object based on Promises. For example:
function defer() {
var deferred = {};
var promise = new Promise(function(resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
deferred.promise = promise;
return deferred;
}
var deferred = defer();
deferred.promise.then(function(data) {
document.body.innerHTML += '<p>Resolved: ' + data + '</p>';
});
document.body.innerHTML = '<p>Deferred created.</p>';
setTimeout(function() {
deferred.resolve(123);
}, 2000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With