var express = require('express');
var GoogleUrl = require('google-url');
var favicon = require('serve-favicon');
var mongo = require('mongodb').MongoClient;
var app = express();
var db;
var googleUrl = new GoogleUrl({key: 'AIzaSyB5i1sdnt6HwzrvsPTBu0FbPiUZrM_BCsk'});
var PORT = 8080;
mongo.connect('mongodb://localhost:27017/url-shortener', function(err, newDb){
if(err){
throw new Error('Database failed to connect');
} else{
console.log('Successfully connected to MongoDB on port 27017');
}
db=newDb;
db.createCollection('sites', {
autoIndexID: true
});
});
app.use(favicon(__dirname+'/public/favicon.ico'));
app.get('/new/*', function(req, res){
var doc;
console.log('This is the url: '+req.params[0]);
googleUrl.shorten(req.params[0], function(err, shortUrl){
if(err){
console.log(err);
}else{
console.log(shortUrl);
}
doc = check_db(req.params[0], shortUrl, db);
});
下面的res.json语句会在其他函数返回值之前运行并返回一个未定义的变量。
res.json(doc);
});
app.listen(process.env.PORT, function(){
console.log('Express listening on: '+PORT);
});
function check_db(longUrl, shortUrl, db){
db.collection('sites').findOne({
'longUrl': longUrl,
'shortUrl': shortUrl
}, function(err, doc){
if(err){
console.log(err);
}if(doc){
在执行下面的语句并返回值之前,将会执行 res.json 语句。
console.log('This site already exists on the database');
return doc;
}else{
save_db(longUrl, shortUrl, db);
}
});
}
function save_db(longUrl, shortUrl, db){
db.collection('sites').insert({
'longUrl': longUrl,
'shortUrl': shortUrl
}, function(err, doc){
if(err){
throw err
}else{
console.log(doc);
}
db.close();
});
}
在上述代码中,res.json语句在GET请求下方定义的函数有机会完成执行之前就被执行了,结果是res.json返回一个未定义的变量。我知道我必须在我的应用程序中实现异步功能(可能是promises?),但我完全不知道如何做!