使用Q 来重新调整 HttpClient 代码 (using Q)
访问量: 2720
refer to: https://github.com/kriskowal/q
and : https://github.com/kriskowal/q/wiki/API-Reference
记住,要点就是: 把普通的方法封装后,这个方法需要在 success 的callback中,返回 defer.resolve, 在 failed 等callback中, 返回defer.reject 即可。
例如: 原来的方法:
function clickImage(e) { //Ti.UI.createAlertDialog({title: 'hi hi hi', message: 'you clicked me'}).show(); var url = "http://siwei.me"; var client = Ti.Network.createHTTPClient({ onload : function(e) { Ti.API.info("Received text: " + this.responseText); alert('success'); }, onerror : function(e) { Ti.API.debug(e.error); alert('error'); }, timeout : 5000 // in milliseconds }); client.open("GET", url); client.send(); }
使用Q 封装之后,是两个方法:
// 原来的调用方法: function clickImage(e) { url = 'http://siwei.me' get_remote_url(url). then(function(response_text) { alert('success in clickImage, response_text.length:' + response_text.length) }). .fail(function(response_text){ alert('failed in clickImage'); }) done(); } function get_remote_url(url) { // 声明 Q.defer. deferred = Q.defer(); client = Ti.Network.createHTTPClient( { onload: function(e) { alert('success in get_remote_url'); Ti.API.info(this.responseText); // 关键1: 在正常返回的情况,返回 resolve 方法。 deferred.resolve(this.responseText); }, onerror: function(e) { Ti.API.error(e); // 关键2: 在异常返回的情况,返回 reject . deferred.reject( new Error('lalala')); alert('faled'); }, timeout: 5000 }) client.open('GET', url); client.send(); // 返回对应的 promise return deferred.promise; }
其实,还有一种形式: 使用Q把整个方法给包起来。 (作用跟jQuery(dom) 很像),喜欢用哪个自己选。调用方法是一样的。(我个人喜欢前一个)例如:
function get_remote_url(url) { // 返回这个Q.Promise(... ) return Q.Promise(function(resolve, reject, notify){ client = Ti.Network.createHTTPClient( { onload: function(e) { alert('success in get_remote_url'); Ti.API.info(this.responseText); //调用 resolve 方法 resolve(this.responseText); }, onerror: function(e) { Ti.API.error(e); alert('faled'); // 调用 reject方法 reject( new Error('lalala')); }, timeout: 5000 }) client.open('GET', url); client.send(); }) }