promise的初步认识,求批。
嵌套调用,上一个结果是后一个函数的请求参数,或者所有的函数完成之后才能去做一件事 例子:
var Q = require("q");
var fun1 = function (data) {
var deferred = Q.defer();
deferred.resolve(data+" fun1");
return deferred.promise;
}
var fun2 = function (data) {
var deferred = Q.defer();
deferred.resolve(data+" fun2");
return deferred.promise;//返回的是promise对象 这里的resolve的结果将作为下一个promise的参数结果
}
var fun3 = function (data) {
var deferred = Q.defer();
deferred.resolve(data+" fun3");
return deferred.promise;
}
var fun4 = function (data) {
var deferred = Q.defer();
deferred.resolve(data+" fun4");
return deferred.promise;
}
function main(data,cb){
fun2("test")
.then(fun3)
.then(fun4)
.done(function(data){//.done用来返回最终的结果
console.log(data);//test fun2 fun3 fun4
},function(err){
//failed
});
}
function main2() {
Q.all([
fun1("test1"), fun2("test2"), fun3("test3")
]).spread(function () {
console.log(arguments);
//结果如下: { '0': 'test1 fun2', '1': 'test2 fun3', '2': 'test3 fun4' }
});
}
main();
main2();
**上述直接运行即可。**(ps:上面只是个例子,下面部分是初步调用的具体例子)
=====================================================================================
下面是对微信请求接口的一个封装,用的就是Promise的思想。
var http=require("https");
var parse = require('url').parse;
var setting = require('../setting.js');
var iconv = require('iconv-lite');
var Q = require("q");
//任用promise 思想来处理回调函数
function get(url){
var info=parse(url);
var deferred = Q.defer();
var options = {
hostname: info.hostname,
port: info.port,
path: info.path,
method: 'GET'
};
var req = http.request(options, function (res) {
res.on('data', function (chunk) {
deferred.resolve(chunk);
});
});
req.on('error', function (e) {
deferred.register();
});
req.end();
return deferred.promise;
}
var getAcToUrl=function(){
var acToUrl='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+setting.appid+'&secret='+setting.secret;
return get(acToUrl);
}
var getTicketUrl= function(data){
var data=JSON.parse(iconv.decode(data,"UTF-8"));
var ticketUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+data.access_token+"&type=jsapi";
return get(ticketUrl);
}
var getMessage=function(callback){
getAcToUrl().then(getTicketUrl).done(callback);
}
exports.getMessage=getMessage;
求批~~看各路大神有无其他方法。