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 문은 실행되지 않고 다른 함수가 값을 반환 할 수있을 때까지 정의되지 않은 변수를 반환합니다.노드 js에서 비동기 콜백을 만드는 방법은 무엇입니까?
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 문은 다음 명령문이 실행되기 전에 실행되어 값을 반환 할 수 있습니다. GET 요청 아래에 정의 된 기능 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 문을 실행합니다. 내 앱 (잠재적으로 약속하겠습니까?)에 비동기 기능을 구현해야한다는 것을 알고 있지만, 그렇게하는 방법은 완전히 손실되었습니다!