Embed a deferred object without using jquery

I want to implement a deferred base object without using jQuery. Here I will only implement completed and fail-safe callbacks with allow and reject functions. and ofCourse binding the promise method with this function.

I am executing the following implementation in pure js (Edited):

 function Deferred() { var d = {}; d.resolve = function() { d.done(arguments); } d.reject = function() { d.fail(arguments); } d.promise = function() { var x = {}; x.done = function(args) { return args; } x.fail = function(args) { return args; } return x; } return d; } var v; var setVal = function() { var d = new Deferred(); setTimeout(function() { v = 'a value'; d.resolve(this); }, 5000); return d.promise(); }; setVal().done(function() { console.log('all done :' + v); }); 

But the above gives an error: Object #<Object> has no method 'fail'

I know that the return object 'd' of the Deferred() function does not have a done () method. And if I return d.promise from Deferred() , it will not have a permit and reject function.

Please indicate what mistake I am making to achieve the simple goal of a pending object.

Here is the fiddle I'm doing: http://jsfiddle.net/SyEmK/14/

+6
source share
1 answer
 function Deferred(){ this._done = []; this._fail = []; } Deferred.prototype = { execute: function(list, args){ var i = list.length; // convert arguments to an array // so they can be sent to the // callbacks via the apply method args = Array.prototype.slice.call(args); while(i--) list[i].apply(null, args); }, resolve: function(){ this.execute(this._done, arguments); }, reject: function(){ this.execute(this._fail, arguments); }, done: function(callback){ this._done.push(callback); }, fail: function(callback){ this._fail.push(callback); } } var v; var setVal = function() { var d = new Deferred(); setTimeout(function() { v = 'a value'; d.resolve(this); }, 5000); return d; }; setVal().done(function() { console.log('all done :' + v); }); 
+18
source

Source: https://habr.com/ru/post/951195/


All Articles