使用node(express)
将数据插入mongo db时遇到问题我的代码如下所示:
router.get('/data/:section/:sort', function(req, res, next) {
//Deleting old data always before writing new
//Image.remove().exec();
var section = req.params.section;
var sort = req.params.sort;
//Link to Igmur API
var url = 'https://api.imgur.com/3/gallery/'+section+'/'+sort+'/1'; //1 at the end is used to get more than 60 images(gives only 60 without it)
request.get({
url: url,
method: 'GET',
headers: {
'Authorization': 'Client-Id XXXXXXXXXXXXX'
}}, function(e, r, body){
var metadata = JSON.parse(body);
for(var i = 0; i<100; i++){
var image = new Image(metadata.data[i])
image.save(function(err, result){
});
};res.render('index', { title: 'SearchAPI' });});});
问题是我只能在循环中看到大约20个对象而不是100个。 所有因为节点只是在save方法完成之前向前跳转。 我怎样才能解决这个问题?提前谢谢
答案 0 :(得分:2)
使用承诺库,例如Q
您基本上需要做的是等待所有save
方法完成。使用等待执行所有内容的Q.all
方法。
var Q = require('q');
var promiseArr = [];
for(var i = 0; i<100; i++){
var imgDefer = Q.defer();
var image = new Image(metadata.data[i])
image.save(function(err, result){
if(err)imgDefer.reject(err);
else imgDefer.resolve()
});
promiseArr.push(imgDefer);
}
Q.all(promiseArr).then (function (){
res.render('index', { title: 'SearchAPI' });
})
答案 1 :(得分:0)
一次又一次地调用数据库是一种错误的做法,最好使用create
并一次传递所有内容。看看下面的代码片段。希望对您有所帮助。
router.get('/data/:section/:sort', function(req, res, next) {
//Deleting old data always before writing new
//Image.remove().exec();
var section = req.params.section;
var sort = req.params.sort;
//Link to Igmur API
var url = 'https://api.imgur.com/3/gallery/'+section+'/'+sort+'/1'; //1 at the end is used to get more than 60 images(gives only 60 without it)
request.get({
url: url,
method: 'GET',
headers: {
'Authorization': 'Client-Id XXXXXXXXXXXXX'
}}, function(e, r, body){
var metadata = JSON.parse(body);
Image.create(metadata.data,(err, result)=>{
//do operations here
res.render('index', { title: 'SearchAPI' });
})
/* WRONG PRACTICE */
// for(var i = 0; i<100; i++){
// var image = new Image(metadata.data[i])
// image.save(function(err, result){
// });
// };
});
});