我能够获取数据,但我似乎无法通过上面的某些方法重新获得结果:
car.js
'use strict';
var Q = require('q');
var pg = require('co-pg')(require('pg'));
var config = require('../../models/database-config');
var car = module.exports = {};
car.find = Q.async(function *(id)
{
var query = 'SELECT id, title, description FROM cars WHERE id = ' + id;
var connectionResults = yield pg.connectPromise(config.connection);
var client = connectionResults[0];
var done = connectionResults[1];
var result = yield client.queryPromise(query);
done();
console.log("value: " + result.rows[0].id);
return result.rows;
});
这会为我的console.log返回一个有效值,所以我知道我收回了数据。
但是现在当我尝试将它传回堆栈时,我似乎在这个方法之后失去了它:
database.js
module.exports = {
models: {
car: _carModel
},
find: Q.async(_find)
};
function _find(carId)
{
_carModel.find(carId)
.then(function(result){
console.log('result[0].id: ' + result[0].id);
return result;
})
.catch(function(error){
console.log("promise error: " + error);
})
.done();
};
所以这也有效,我得到一个有效的console.log值('结果[0] .id:' + result [0] .id);
但是现在尝试调用此函数时,我失去了结果:
gateway.js
var car = database.find(carId);
console.log("car: " + car.id);
...
这里我得到'Cannot read property 'id' of undefined]'
更新#2
所以我现在尝试传播承诺,但仍然未定义行console.log("返回汽车数据:" +数据); '数据'未定义。
gateway.js
module.exports = {
data: function(someData){
_data = someData;
},
find: function(text, result){
if(!text){
results(null);
};
var endpoint = _endpoint.replace(/_text/g, text);
_client.query(endpoint, function(results){
var cars = [];
var car;
for (var i = 0; i < results.docs.length; i++){
var carId = results.docs[i].id;
car = database.find(carId)
.then(function(data){
console.log("returned car data: " + data);
})
.done();
cars.push(car);
}
result(cars);
});
}
database.js
'use strict';
var Q = require('q');
var _obituaryModel = require('../../models/postgreSQL/obituary');
module.exports = {
models: {
obituary: _carModel
},
find: Q.async(_find)
};
function _find(carId)
{
_carModel.find(carId)
.then(function(result){
console.log('result[0].id: ' + result[0].id);
return result;
})
.catch(function(error){
console.log("promise error: " + error);
})
.done();
};
carModel.js
'use strict';
var Q = require('q');
var pg = require('co-pg')(require('pg'));
var config = require('../../models/database-config');
var car = module.exports = {};
car.find = Q.async(function *(id)
{
var query = 'SELECT id, title, description FROM cars WHERE id = ' + id;
var connectionResults = yield pg.connectPromise(config.connection);
var client = connectionResults[0];
var done = connectionResults[1];
var result = yield client.queryPromise(query);
done();
console.log("value: " + result.rows[0].id);
return result.rows;
});
答案 0 :(得分:0)
您无法从异步函数返回数据。
见这里:How to return value from an asynchronous callback function?
答案 1 :(得分:0)
您正在控制台上打印if ((int) $e->getCode() === 23000) { echo 'unique error' }
,但在实际通话中阅读result[0].id
:
尝试
result.id
答案 2 :(得分:0)
你有一个承诺对象,可以使用它。
在 database.js:
中std::vector
和 gateway.js
["1","2","3","4"]