You can use Promise standard object instead of JSDeferred now!
JSDeferred is born before Promise. It is no longer necessary to use JSDeferred because you can use the standard Promise now.
Asynchronous library in JavaScript. Standalone and Compact.
Home Page: http://cho45.stfuawsc.com/jsdeferred/
You can use Promise standard object instead of JSDeferred now!
JSDeferred is born before Promise. It is no longer necessary to use JSDeferred because you can use the standard Promise now.
AS移植していたのですが、chain
の例を実行してみると最後まで実行されない現象を確認しました。
nodeで確認するとJSDeferred側のchain
も最後まで実行されないようです。
jsdeferred/jsdeferred.js at master · cho45/jsdeferred
jsdeferred.jsの333行目
{
foo: wait(1),
bar: wait(1)
},
オブジェクトの中のwait
が即時実行されているようだったのでfunction () {}
で囲ってあげると最後まで実行されました。
{
foo: function () {
return wait(1);
},
bar: function () {
return wait(1);
}
},
直し方としてあってますでしょうか?
Idea
Deferred.define()
しないで
Deferred.parallel([
function () { return "hoge"; },
]).next(function (values) {
alert(values);
});
を実行すると、「nextが定義されていない」という内容のエラーになってしまいます。
コードを読むと、Deferred.parallelとDeferred.chainは、どうやらDeferred.define()されていることが前提で書かれているようです(ほかにもあるかもしれません)。
修正していただけると幸いです。
とりあえず Deferred.methods にしてみたバージョンを作ったのですが、rhino 環境をどう用意すればよいか分からずテストできません。(あと node.js や Worker 内で動かすために typeof window === 'object' チェックを入れています)
http://github.com/edvakf/jsdeferred/blob/master/jsdeferred.js
IE8において(恐らくIE6も)、httpsのページでJSDeferredを使った場合に、Deferred.nextを連続で呼ぶと、「セキュリティで保護された Web ページ コンテンツのみを表示しますか」が発生します。
再現するコード例(このHTMLをhttpsでアクセス): http://gist.github.com/205896
原因は、Deferred.next_faster_way_readystatechange で作っている<script>タグだと思います。
src="javascript:" ではなく、 src="" として<script>タグを生成するとこの警告は止まりましたが、DOMの扱いとして正しいかちょっと自信がないです。
Google Chrome have no GM_xmlhttpRequest, but old good XMLHttpRequest instead.
So, http://github.com/cho45/jsdeferred/blob/master/jsdeferred.userscript.js doesn't work.
Google Chrome's XMLHttpRequest can do x-domain requests. jsdeferred.userscript.js could try to do XMLHttpRequest, if no GM_xmlhttpRequest available.
Right now, I can't port diff_for_gist.user.js to Chrome because of jsdeferred.userscript.js.
Deferred.parallel([ 1, 2, 3 ].map(function(i) {
var d = new Deferred;
setTimeout(function() {
d.fail(i);
});
return d;
})).error(console.log.bind(console));
// => 1
// => 2
// => 3
Since you will get only one result for a succeeded paralleled-deferred I guess there shouldn't be three results for a failed paralleled-deferred.
// in this code "d" may be not Deferred
str 456: if (typeof d == "function") d = Deferred.next(d);
// in this code "d" always Deferred
str 474 : for (var i in dl) if (dl.hasOwnProperty(i)) {
str 475 : dl[i].cancel();
str 476 : }
is a bug or I do not understand the code correctly?
Deferred.parallel = function (dl) {
if (arguments.length > 1) dl = Array.prototype.slice.call(arguments);
var ret = new Deferred(), values = {}, num = 0;
for (var i in dl) if (dl.hasOwnProperty(i)) (function (d, i) {
if (typeof d == "function") d = Deferred.next(d);
d.next(function (v) {
values[i] = v;
if (--num <= 0) {
if (dl instanceof Array) {
values.length = dl.length;
values = Array.prototype.slice.call(values, 0);
}
ret.call(values);
}
}).error(function (e) {
ret.fail(e);
});
num++;
})(dl[i], i);
if (!num) Deferred.next(function () { ret.call() });
ret.canceller = function () {
for (var i in dl) if (dl.hasOwnProperty(i)) {
dl[i].cancel();
}
};
return ret;
};
underscore.js has a quite useful _.throttle function that prevents too frequent function invocation.
http://documentcloud.github.com/underscore/#throttle
This could also be a useful parameter for jsdeferred's parallel function (only execute a maximum of n parallel functions concurrently - queue the execution of the rest meanwhile)
Hi,
I'm writing a javascript client for a webservice that requires a lot of inter-dependent requests (i.e. you need the parts of the response from request1 as GET parameters in request 2). To avoid the extensive use of nested callbacks, I like to develop the client using jquery/jsdeferred's next statement. To make my code even shorter, I like to register my custom request/response handler as Deferred shorthand function. Here is what I have so far:
Deferred.define();
function makeRequest (method, params){
$.extend(params,{method: method, api_key: 123});
var url = $.param('http://api.example.com', params);
return next($.get(url))
}
Deferred.define(makeRequest, ["next","parallel"]);
makeRequest('getIdForUsername', {username:'dummy'}).
//user_id is from the response of 'getIfForUsername' request
makeRequest('getUserStatus', {user_id:user_id}).
next(function(userstatus){
//generate HTML for user status
});
My questions:
Thanks for developing jsdeferred!
Franz
// --------------- Here order of log is 2 -> 1 , child redirect works wrong function showData(data) { var fadeout = Deferred.connect($.fn.fadeOut, { target: $('#container'), ok:1 }); return fadeout(500). next(function() { return $('#container') .text(data) .deferred("fadeIn", 2000) .next(function() { console.log(1) }) }). next(function() { console.log(2) }) }
/**
* Create future object
*
* @example
* var token = future(future () {
* return $.getJSON('/api/token').next(function (data) { return data.token });
* });
*
* token.next(function (token) {
* alert(token);
* });
*
* token.next(function (token) {
* console.log(token);
* });
*
* token.next(function (token) {
* // Use token
* }).
* error(function (e) {
* alert(e);
* });
*
* Future is like Deferred object but it behaves as "future" value (deferred process and future value).
* Actually, this object is for a recycling value of Deferred.
*
* @param {function():Deferred} function returns Deferred which has a value for recycling.
* @return {{next:function()}} Future object is has only 'next' function which return Deferred object.
*/
function future (fun) {
var d = fun();
var state, value;
var waiting = [];
d.
next(function (val) {
state = "call";
value = val;
}).
error(function (err) {
state = "fail";
value = err;
}).
next(function () {
for (var i = 0, it; (it = waiting[i]); i++) {
it[state](value);
}
});
return {
next : function (cb) { /* return new Deferred */
var d = new Deferred();
d.next(cb);
if (state) {
d[state](value);
} else {
waiting.push(d);
}
return d;
}
};
}
var val = future(function () {
return Deferred.wait(0.5);
});
val.next(function (v) {
console.log(v);
val.next(function (v) {
console.log(v);
});
});
Chrome dev tools complaints
Resource interpreted as image but transferred with MIME type text/plain.
Just adding image/png will remove this complaits
First, thank you for the fine script.
If I run a script in Firefox I see "Image corrupt or truncated: data:image/png.." at the Javascript error console.
This also happens on your demo page. In other browsers it seems okay.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.