pdownFile= P.coroutine(function*(fileUrl)
{
var options = {
host: url.parse(fileUrl).host,
port: 80,
path: url.parse(fileUrl).pathname
};
var self=this;
var file_name = decodeURI(url.parse(fileUrl).pathname.split('/').pop());
var filePath=this.downloadDir + file_name;
var file = fs.createWriteStream(filePath);
var Ticker=function(){};
util.inherits(Ticker,Et);
var ticker = new Ticker();
var loaded = new Promise(function(resolve, reject) {ticker.on("tick", resolve);});
//catch 捕获回调的第一个参数,通常情况下是err参数,这里是res
phttp.getAsync(options).catch(function(res)
{
res.on('data', function(data) {
file.write(data);
});
res.on('end', function(){
file.end();
//cb(filePath);
console.log(file_name + ' downloaded to ' + self.downloadDir);
ticker.emit('tick');
});
console.log('event tick');
});
return filePath;
});
{
var options = {
host: url.parse(fileUrl).host,
port: 80,
path: url.parse(fileUrl).pathname
};
var self=this;
var file_name = decodeURI(url.parse(fileUrl).pathname.split('/').pop());
var filePath=this.downloadDir + file_name;
var file = fs.createWriteStream(filePath);
var Ticker=function(){};
util.inherits(Ticker,Et);
var ticker = new Ticker();
var loaded = new Promise(function(resolve, reject) {ticker.on("tick", resolve);});
//catch 捕获回调的第一个参数,通常情况下是err参数,这里是res
phttp.getAsync(options).catch(function(res)
{
res.on('data', function(data) {
file.write(data);
});
res.on('end', function(){
file.end();
//cb(filePath);
console.log(file_name + ' downloaded to ' + self.downloadDir);
ticker.emit('tick');
});
});
//这里实现对异步函数同步逻辑
yield loaded.then(function(){console.log('event tick');
});
return filePath;
});

本文介绍了如何借助Bluebird库的Promise,将Node.js中的HTTP下载异步调用转换为同步逻辑,以提高代码的可读性和控制流程。
1379

被折叠的 条评论
为什么被折叠?



