2016年2月22日 星期一

nodejs promise Q, Bluebird , async

bluebird

Async is a library for managing asynchronous operations that is not based on the use or design of promises.

================  1  file write nest ===============

fs.writeFile('./'+foldername+'/'+plist.filename, generatePlistContect(plist), function (err) {
   if (err)
       return console.log(err);
   console.log('Hello World > helloworld.txt');


fs.writeFile('./'+foldername+'/'+html.filename, generateHtmlContect(html), function (err) {
   if (err)
       return console.log(err);
   console.log('Hello World > helloworld2.txt');

console.log('going to index');
res.render('index', { title: foldername+" is created in basic" });
});
});


================  2  file write promise ===============

var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));

fs.writeFileAsync('./'+foldername+'/'+plist.filename, generatePlistContect(plist))
.then(function(){
        return fs.writeFileAsync('./'+foldername+'/'+html.filename, generateHtmlContect(html))
    }).then(function(){
    res.render('index', { title: foldername+" is created in promise" });
    }).catch(function(error){
    res.render('index', { title: error });
});
================  3  file write parallel ===============
var Promise = require("bluebird");
var fs = Promise.promisifyAll(require("fs"));

var pro = [];

pro.push(fs.writeFileAsync('./'+foldername+'/'+plist.filename, generatePlistContect(plist)))
pro.push(fs.writeFileAsync('./'+foldername+'/'+html.filename, generateHtmlContect(html)))

Promise.all(pro).then(function() {
     res.render('index', { title: foldername+" is created in promise_parallel" });
}).catch(function(error){
     res.render('index', { title: error });
});



沒有留言:

張貼留言