利用bluebird的promise 實現nodejs http下載異步調用的同步邏輯

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');
             });

     });

//這裏實現對異步函數同步邏輯

    yield loaded.then(function(){
        console.log('event tick');
    });


    return filePath;


});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章