I'm really stuck here. Promises, by definition, only return once. However, I need to figure out a way to get promises working with the cron module. Below is a shortened version of what I'm trying to do. Everything executes just fine the first time but after that the promise never resolves.
Unfortunately I'm stuck using the node-pool module which is where the promise comes from. This module is required for connection pooling with HANA databases.
Thanks!
var pool = require('generic-pool');
var servers = require('../config/servers');
var CronJob = require('cron').CronJob;
var hdb = require('hdb'); // database driver
var factories = {};
var pools = {};
for (let i = 0; i < servers.length; i++) {
factories[servers[i].name] = {
create: function(){
return new Promise(function(resolve, reject){
var client = hdb.createClient({
host: servers[i].host,
port: servers[i].port,
user: servers[i].user,
password: servers[i].password
});
resolve(client);
});
},
destroy: function(client){
if (!client.hadError && client.readyState !== 'closed') {
client.end();
}
}
};
pools[servers[i].name] = pool.createPool(factories[servers[i].name]);
}
var job = new CronJob({
cronTime: '0 * * * *',
onTick: () => {
async.waterfall([
(callbackWF) => {
var resourcePromise = pools[name].acquire();
console.log(moment().format('YYYY-MM-DD HH:mm:ss.SS - ') + 'Attempting to resolve promise for Name: ' + name + ' Table: ' + table);
resourcePromise.then( (client) => {
console.log(moment().format('YYYY-MM-DD HH:mm:ss.SS - ') + 'Got promise for Name: ' + name + ' Table: ' + table);
if (client.readyState != 'connected') {
client.connect( (err) => {
if (err) {
console.log(moment().format('YYYY-MM-DD HH:mm:ss.SS - ') + 'Error while connecting to client. Name: ' + name + ' Host: ' + host + ' Port: ' + port + ' User: ' + user + ' Error: ' + JSON.stringify(err));
return callbackWF('error', client);
}
callbackWF(null, client);
});
} else {
callbackWF(null, client);
}
}).catch( (err) => {
if (err) {
console.log(moment().format('YYYY-MM-DD HH:mm:ss.SS - ') + 'Error getting promise for connection pool. Name: ' + name + ' Host: ' + host + ' Port: ' + port + ' User: ' + user + ' Error: ' + JSON.stringify(err));
callbackWF('error');
}
console.log(moment().format('YYYY-MM-DD HH:mm:ss.SS - ') + 'Caught promise');
});
},
// Get data for table.
(client, callbackWF) => {
client.exec(select, {rowsAsArray: true}, (err, rows) => {
if (err) {
console.log(moment().format('YYYY-MM-DD HH:mm:ss.SS - ') + 'Error while getting data from ' + name + " table: " + table + ". " + err + select);
return callbackWF(err, client);
}
callbackWF(null, client);
});
}
], (err, client) => {
if (typeof client != 'undefined') {
console.log(moment().format('YYYY-MM-DD HH:mm:ss.SS - ') + 'Releasing pool for Name: ' + name + ' Table: ' + table);
pools[name].release(client);
}
});
},
start: true,
timeZone: 'UTC'
});
I don't see anything wrong with this. A promise might only return once, but you can totally call then() on it as many times as you want.
Related
I've got into an issue. Postgres code(query) is not executed at all. I have to mention that the connection with the DB is correctly done.
I've tried to debug the code but I don't really know what's the problem
'use strict';
const config = require('../config');
const emailService = require('./email-service');
const pg = require('pg');
pg.defaults.ssl = true;
module.exports = function(phone_number, user_name, previous_job, years_of_experience, job_vacancy){
console.log('sending email');
let emailContent = 'A new job inquiry from ' + user_name + ' for the job: ' + job_vacancy +
'.<br> Previous job position: ' + previous_job + '.' +
'.<br> Years of experience: ' + years_of_experience + '.' +
'.<br> Phone number: ' + phone_number + '.';
emailService.sendEmail('New job application', emailContent);
try{
var pool = new pg.Pool(config.PG_CONFIG);
pool.connect(function(err, client, done) {
if (err) {
return console.error('Error acquiring client', err.stack);
}
client
.query(
'INSERT into job_applications ' +
'(phone_number, user_name, previous_job, years_of_experience, job_vacancy) ' +
'VALUES($1, $2, $3, $4, $5) RETURNING id',
[phone_number, user_name, previous_job, years_of_experience, job_vacancy],
function(err, result) {
if (err) {
console.log(err);
} else {
console.log('row inserted with id: ' + result.rows[0].id);
}
});
});
}
catch(e){
console.log(e, 'error[][][]')
}
pool.end();
} ```
I have a function called postGirl that posts an image of an anime girl onto my twitter account. The images all download fine, so I have a folder that generates 400 images named girl1.jpg - girl400.jpg, so that doesn't seem to be the issue.
let postGirl = (girl, girlNum) => {
let numOfGirl = girlNum + 1;
let girlImage = './img/girl' + numOfGirl + '.jpg';
var girlImageFinal = girl[3];
console.log(girlImage);
let author = girl[0];
let tags = girl[1];
let hashtags = girl[2];
console.log('posting?');
var b64content = fs.readFileSync(girlImage, { encoding: 'base64' })
OtakuBot.post('media/upload', { media_data: b64content }, function (err, data, response) {
var mediaIdStr = data.media_id_string
var altText = 'Cute Girl'
var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }
console.log('inside media/upload');
OtakuBot.post('media/metadata/create', meta_params, function (err, data, response) {
if (!err) {
let postMessage = '';
console.log(tags[0]);
postMessage = 'Cute picture with ' + tags[0] + ' and ' + tags[1] + ' by ' + author + ' #animegirls #' + author + ' #' + hashtags[0] + ' #' + hashtags[1] + ' #' + hashtags[2];
var params = { status: postMessage, media_ids: [mediaIdStr] }
OtakuBot.post('statuses/update', params, function (err, data, response) {
console.log(data)
})
} else {
console.log(err);
}
})
})
}
I keep getting this error:
Error: media_id field must be provided.
at Object.exports.makeTwitError (C:\Users\Atlow\Documents\otakubot\node_modules\twit\lib\helpers.js:74:13)
at onRequestComplete (C:\Users\Atlow\Documents\otakubot\node_modules\twit\lib\twitter.js:344:25)
at Request.<anonymous> (C:\Users\Atlow\Documents\otakubot\node_modules\twit\lib\twitter.js:364:7)
at Request.emit (events.js:327:22)
at Gunzip.<anonymous> (C:\Users\Atlow\Documents\otakubot\node_modules\request\request.js:1076:12)
at Object.onceWrapper (events.js:421:28)
at Gunzip.emit (events.js:315:20)
at endReadableNT (_stream_readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
code: null,
allErrors: [
{
request: '/1.1/media/metadata/create.json',
error: 'media_id field must be provided.'
}
],
twitterReply: {
request: '/1.1/media/metadata/create.json',
error: 'media_id field must be provided.'
},
statusCode: 400
}
did you checked out the data.media_id_string is not undefined in callback function?
I am trying to print all the characteristics for my RealME-1 phone wsing Google's web bluetooth API. The code goes like:
navigator.bluetooth.requestDevice(options)
.then(device => {
log('> Name: ' + device.name);
log('> Id: ' + device.id);
log('> Connected: ' + device.gatt.connected);
log('>device '+device);
return device.gatt.connect();
})
.then(server => {
log('Getting Service...');
return server.getPrimaryService(serviceUuid);
})
.then(service => {
log('Getting Characteristic...');
return service.getCharacteristic(characteristicUuid);
})
.then(characteristic => {
log('> Characteristic UUID: ' + characteristic.uuid);
log('> Broadcast: ' + characteristic.properties.broadcast);
log('> Read: ' + characteristic.properties.read);
log('> Write w/o response: ' +
characteristic.properties.writeWithoutResponse);
log('> Write: ' + characteristic.properties.write);
log('> Notify: ' + characteristic.properties.notify);
log('> Indicate: ' + characteristic.properties.indicate);
log('> Signed Write: ' +
characteristic.properties.authenticatedSignedWrites);
log('> Queued Write: ' + characteristic.properties.reliableWrite);
log('> Writable Auxiliaries: ' +
characteristic.properties.writableAuxiliaries);
})
.catch(error => {
log('Argh! ' + error);
});
However when testing it gets stuck at device.gatt.connect() . Any ides where am I missing?
Thanks
I'm developing a Hybrid App using Intel XDK and power of Cordova. For using SQLite I'm using cordova-sqlite-storage BUT have problem to fetch the data ! I'm using this codes ...
function onDeviceReady() {
var appDataBase = window.sqlitePlugin.openDatabase({name: 'DB.db', location: 1}, onSuccess_DB, onFail_DB);
getPageContent('about-app', 'page-about');
}
function getPageContent(pageID, outputDIV) {
appDataBase.transaction(function(dbDataSet) {
dbDataSet.executeSql("SELECT page_content FROM app_pages WHERE page_id='" + pageID + "'", [], function(dbDataSet, dbDataOutput) {
if (dbDataOutput.rows.length == 1) {
console.log('Get Page Content : ' + pageID);
$('#' + outputDIV).html(dbDataOutput.rows.item(0).page_content);
} else {
console.log('Get Page Content : Count ERROR : ' + dbDataOutput.rows.length);
$('#' + outputDIV).html('NOT Found');
}
}, function(e) {
console.log('Get Page Content : DB ERROR : ' + e.message);
});
});
}
What shall I do !?
Check with this code
function getData(last) {
db.transaction(function (tx) {
alert("get data");
var query = "SELECT firstname, lastname, acctNo FROM customerAccounts WHERE lastname = ?";
alert("get data working");
tx.executeSql(query, [last], function (tx, resultSet) {
for(var x = 0; x < resultSet.rows.length; x++) {
alert("First name: " + resultSet.rows.item(x).firstname +
", Acct: " + resultSet.rows.item(x).acctNo);
}
},
function (tx, error) {
alert('SELECT error: ' + error.message);
});
}, function (error) {
alert('transaction error: ' + error.message);
}, function () {
alert('transaction ok');
});
}
I am using a button to go to the delete route and I am passing to it a key to identify which team to delete. Instead of deleting just one team it deletes ALL teams when using the route. Any ideas?
Delete button:
button#teamDelete.btn.btn-danger.btn-mini(type="submit", value="Delete Team") Delete
script(type='text/javascript')
$('#teamDelete').live('click',function(){
var teamId = #{teamData.key};
$.post('/team/' + teamId, { _method : 'delete' }, function(response) {
console.log(response);
});
});
Team routes:
app.get('/team'/*, lim("Must be logged in to see teams")*/, getAllTeams, function(req, res){
util.log('Serving request for url [GET] ' + req.route.path);
// Pass it the list of all Teams
res.render('team', {'teamsList' : req.teamsList} );
});
/**
* POST /team
* Save new Team
*/
app.post('/team', function(req, res) {
util.log('Serving request for url [POST] ' + req.route.path);
// Output to console the contents of req.body
// console.log('body: ', req.body);
// console.log('body.teamForm: ', req.body.teamForm);
// console.log('body.teamForm.name: ', req.body.teamForm.name);
// console.log('body.teamForm.teamKey: ', req.body.teamForm.teamKey);
// Get data from teamForm
var teamForm = req.body.teamForm;
// Save team in teamForm as new Team
var name = teamForm.name;
var team = new Team();
team.name = name;
// Save new Team to datbase
team.save(function(err){
var message = '';
var retStatus = '';
// No error - Successful Save
if(!err){
util.log('Successfully created new team: ' + name);
message = 'Successfully created new team: ' + name;
retStatus = 'success';
}
// Error - Unsuccessful Save, show error
else {
util.log('Error while creating team: ' + name + ' error : ' + util.inspect(err));
if(err.code === 11000){
message = 'Team already exists';
}
retStatus = 'failure';
}
// Return whether the Save was successful
res.json({
'retStatus' : retStatus,
'message' : message
});
});
});
/**
* GET /team/:key
* Get Team details by key
*/
app.get('/team/:key', function(req, res) {
util.log('Serving request for url [GET] ' + req.route.path);
Team.findByKey(req.params.key, function(err, teamData){
if(!err && teamData){
teamData = teamData;
res.render('teamDetails', { 'teamData' : teamData } );
} else {
util.log('Error in fetching Team by key : ' + req.params.key);
res.json({
'retStatus' : 'failure',
'msg' : 'Error in fetching Team by key ' + req.params.key
});
}
});
});
/**
* DEL /team/:key
* Delete Team by key
*/
app.del('/team/:key', function(req, res) {
util.log('Serving request for url [DEL] ' + req.route.path);
util.log(req.params.key);
Team.remove(req.params.key, function(err){
var message = '';
var retStatus = '';
if (!err) {
util.log('Successfully deleting Team with key: ' + req.params.key);
message = 'Successfully deleting Team with key: ' + req.params.key;
retStatus = 'Success';
} else {
util.log('Error deleting Team with key: ' + req.params.key + 'Error: ' + util.inspect(err));
res.json({
'retStatus' : 'failure',
'msg' : 'Error in fetching Team with key ' + req.params.key
});
}
});
});
Well, you haven't indicated, but I presume Team is a mongoose model, in which case you are not properly specifying your conditions parameter, which must be an object of key/value criteria. Try:
Team.remove({key: req.params.key}, function (err) {});
http://mongoosejs.com/docs/api.html#model_Model.remove