Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update beginners-guide.md #1475

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Update beginners-guide.md
Added simple example how to use bluebird. I faced issue finding basic code to implement bluebird. So I added few lines of code for other people to have an easy way to begin with.
  • Loading branch information
vverma508 committed Nov 6, 2017
commit f55f81d38d97fea994d75bdb161e01c4784321ec
59 changes: 59 additions & 0 deletions docs/docs/beginners-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,62 @@ title: Beginner's Guide
---

[beginners-guide](unfinished-article)

proper implementation of bluebird will help you chain your function synchronously.

Example 1 :

Code :

var express = require('express');
var fs = require('fs');
var app = express();


app.get('/index', function(req,res){
var index =fs.readFile('./views/index.html', 'utf8') //Async function
res.send(index)
});
var port = process.env.PORT || 3000
app.listen(port, function () {
console.log("Server is running at:" + port)
})

In above code, it is suppose to fetch the index.html file and then send the response. But when you run it, it will not return you anything but an empty page.
Reason : fs.readFile is an async methods, so even before read operation is completed action is passed to next command which is res.send.
So empty response is sent.

## Solution with bluebird

code :

var express = require('express');
var promise = require('bluebird');
var fs = require('fs');
var app = express();
var index;
var getIndex = function(){
return new promise(function(resolve,reject){

fs.readFile('./views/index.html', 'utf8', function(err,data){
if(err){
reject(err);
}
else{
index=data;
resolve(index);
}
})
})
};

app.get('/index', function(req,res){
getIndex().then( function(){ //bluebird promise objects make sures that next command is executed only once promise is either resolved or rejected.
res.send(index)
});
})

var port = process.env.PORT || 3000
app.listen(port, function () {
console.log("Server is running at:" + port)
})