node js function.then in not a function using q - node.js

Hello its so wired i am trying to do async function but when i use it i get error
using q
on package json
"q": "^1.4.1"
TypeError: helper.setNextUserNewsAction(...).then is not a function
this is my helper
module.exports = function() {
return {
setNextUserNewsAction: setNextUserNewsAction
}
}();
function setNextUserNewsAction(minutesToSet){
var defer = q.defer();
var x = minutesToSet;
var d = new Date();
var nextNews = new Date(d.getTime() + x*60000);
var minutes = nextNews.getMinutes();
var newMinutesToSet = 0;
for (var i = 0 , j = minutesToSet; j <= 60; i+=minutesToSet,j+=minutesToSet) {
if (minutes > i && minutes < j)
return newMinutesToSet = (i % 60);
}
nextNews.setMinutes(newMinutesToSet);
nextNews.setSeconds(00);
var NextNewsAction = {
AccessDate: nextNews,
Type: 'News',
Current: 1
}
defer.resolve(NextNewsAction);
return defer.promise;
}
and when i call this function in my controller it send me that error
var helper = require('../helpers/playlist');
helper.setNextUserNewsAction(15).then(function(action){
console.log(action);
},function(err){
console.log(err);
});
i have also try doing that with try and catch and still same error
well its not the first time or the 20 i am using q
hope somebody can help

The problem is that you are returning something from the for loop:
for (var i = 0, j = minutesToSet; j <= 60; i += minutesToSet, j += minutesToSet) {
if (minutes > i && minutes < j)
return newMinutesToSet = (i % 60);
}
So the setNextUserNewsAction function is not returning a promise, therefore there is no .then().
Try this:
var q = require('q');
module.exports = function() {
return {
setNextUserNewsAction: setNextUserNewsAction
}
}();
function setNextUserNewsAction(minutesToSet){
var defer = q.defer();
var x = minutesToSet;
var d = new Date();
var nextNews = new Date(d.getTime() + x*60000);
var minutes = nextNews.getMinutes();
var newMinutesToSet = 0;
for (var i = 0, j = minutesToSet; j <= 60; i += minutesToSet, j += minutesToSet) {
if (minutes > i && minutes < j) {
newMinutesToSet = (i % 60);
}
}
nextNews.setMinutes(newMinutesToSet);
nextNews.setSeconds(00);
var NextNewsAction = {
AccessDate: nextNews,
Type: 'News',
Current: 1
}
defer.resolve();
return defer.promise;
}

Related

Callback and event emitter functionality using NodeJS

Programme language is NodeJS
Steps ToDo:
1. The variable input has the input value. Extract n1 and n2 from the input.
2. Write a function to find the sum of all the multiples of n1 and n2, below and including 1000. This function should log the sum after 2 seconds.
3. Register an event named MyEvent for any instance of an event emitter, and bind a function named logInfo to it, which logs "Multiples of {n1} & {n2}" to the console and emit the event(Don't pass any parameters while emitting the event).
Constraints
Input: input, a string separated by space
Output: strings separated by newline
Note: Even though you got the exact output, the test cases will fail if you do not use the callback and event concepts as mentioned in the problem statement.
Sample Case 0
Sample Input For Custom Testing
100 1000
Sample Output:
Multiples of 100 & 1000
6500
Explanation
Multiples of 100 are 100,200,300,......1000 and multiples of 1000 is 1000 in below and including 1000.
Sum = (100+200+............1000) + 1000
Sum = 6500
Sample Case 1
Sample Input For Custom Testing
500 1200
Sample Output:
Multiples of 500 & 1200
1500
I Tried below code :
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
input += chunk;
});
process.stdin.on("end", function () {
let _input = input.split (" ");
let a = parseInt(_input[0]);
let b = parseInt(_input[1]);
console.log("Multiples of " + a + " & " + b);
var sum = 0;
for (var x = 0; x < 1000; x++)
{
if (x % a === 0 || x % b === 0)
{
sum += x;
}
}
console.log(sum);
});
Code Test out:
Case 1
Input (stdin)
4 6
Your Output (stdout)
Multiples of 4 & 6
165834
Expected Output
Multiples of 4 & 6
208666
===============================================
Case 2
Input (stdin)
3 5
Your Output (stdout)
Multiples of 3 & 5
233168
Expected Output
Multiples of 3 & 5
267333
Please help me for this code. My output is not match with this logic.
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
input += chunk;
});
process.stdin.on("end", function () {
const myArr = input.split(" ");
const EventEmitter = require('events');
var eventEmitter = new EventEmitter();
let sum=0;
let a = myArr[0];
let b = myArr[1];
for(let i=3; i<=1000; i++){
if(i%a==0){
sum += i
}
if(i%b==0){
sum+=i
}
}
eventEmitter.on('MyEvent', function(){
setTimeout(function(){
console.log("Multiples of " + a + " & "+ b);
console.log(sum);},5000);
});
eventEmitter.emit('MyEvent');
});
I got the right solution.
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
input += chunk;
});
process.stdin.on("end", function () {
const EventEmitter = require('events');
let data = input.split(" ");
n1 = data[0];
n2 = data[1];
// console.log(n1,n2);
let result = 0;
const sum = () => {
for (let i = 0; i <= 1000; i++) {
if (i % n1 == 0) {
result += i;
}
}
for (let j = 0; j <= 1000; j++) {
if (j % n2 == 0) {
result += j;
}
}
console.log(result);
}
setTimeout(sum, 2000);
const event = new EventEmitter();
event.on("MyEvent", () => {
console.log(`Multiples of ${n1} & ${n2}`);
})
event.emit("MyEvent");
});
I hope below code will help you and will give expected output. Thanks! :)
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
input += chunk;
});
process.stdin.on("end", function () {
const myArr = input.split(" ");
const EventEmitter = require('events');
var eventEmitter = new EventEmitter();
let sum=0;
let a = myArr[0];
let b = myArr[1];
for(let i=3; i<=1000; i++){
if(i%a==0){
sum += i
}
if(i%b==0){
sum+=i
}
}
eventEmitter.on('MyEvent', logInfo);
function logInfo(input) {
console.log("Multiples of " + a + " & "+ b);
console.log(sum);
}
eventEmitter.emit('MyEvent', "");
});
Check below solution
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
input += chunk;
});
process.stdin.on("end", function () {
const myArr = input.split(" ");
const EventEmitter = require('events');
var eventEmitter = new EventEmitter();
let sum=0;
let a = myArr[0];
let b = myArr[1];
for(let i=3; i<=1000; i++){
if(i%a==0){
sum += i
}
if(i%b==0){
sum+=i
}
}
eventEmitter.on('MyEvent', logInfo);
function logInfo(input) {
console.log("Multiples of " + a + " & "+ b);
console.log(sum);
}
eventEmitter.emit('MyEvent', "");
});
I have only call console as async function kindly avoid my mistake.
process.stdin.on("end", function () {
// Enter your code here
const myArr = input.split(" ");
const EventEmitter = require('events');
var eventEmitter = new EventEmitter();
let sum=0;
let a = myArr[0];
let b = myArr[1];
for(let i=3; i<=1000; i++){
if(i%a==0){
sum += i
}
if(i%b==0){
sum+=i
}
}
setTimeout(function(){
console.log(sum);
},2000)
eventEmitter.on('MyEvent', logInfo);
function logInfo() {
console.log("Multiples of " + a + " & "+ b);
}
eventEmitter.emit('MyEvent');
});

Node.js for loop output only last item from JSON

The code below only output the last result, I don't get it. I check if the updateDate item contains 2020-05 both items does and I get only the last one. The loop is not looping :)
const briefing = [
{
"updateDate": "2020-05-05T00:00:00.0Z",
},
{
"updateDate": "2020-05-06T00:00:00.0Z",
},
{
"updateDate": "2020-05-13T00:00:00.0Z",
}
];
let date = new Date();
var formattedYearMonth = date.getFullYear() + '-' + ('0' + (date.getMonth()+1)).slice(-2) + '-';
for (var i = 0; i < briefing.length; i++) {
var jsonDate = briefing[i].updateDate;
if (jsonDate.includes(formattedYearMonth)) {
var response = JSON.stringify(briefing[i]);
}
}return response;
}
for (var i = 0; i < briefing.length; i++) {
var jsonDate = briefing[i].updateDate;
if (jsonDate.includes(formattedYearMonth)) {
var response = JSON.stringify(briefing[i]); // <==== THIS IS WHERE YOUR PROBLEM LIES
}
}return response;
The loop is actually looping :). But for every run of the loop, you are resetting the value of response.
--EDITED--
For the response to be an array, you need to modify your code as
let response = [];
for (var i = 0; i < briefing.length; i++) {
var jsonDate = briefing[i].updateDate;
if (jsonDate.includes(formattedYearMonth)) {
response.push(JSON.stringify(briefing[i]));
}
}
return response;

Problem with findOne() in sequelize node.js

I have a problem with node.js and sequelize findOne(). I want to find new students, that I want to add to the DB (var novi), and the ones that already exist, I just want to update their field (var stari). Everything works as expected, only when I want to return JSON with how many new students I added to the DB, and how many are updated, values of stari and novi, go back to 0, but the counting is good, I checked. I know the problem is with asynchronous call, but I don't know how to fix.
app.post('/student', function(req,res) {
var imeGodine = req.body['godina'];
//POMOĆNE SKRIPTE BitBucket.js i citanjeGodina.js
var broj = 0;
var stari = 0;
var novi = 0;
db.godina.findOne({where:{nazivGod:req.body.godina}}).then(god => {
var studenti = req.body.studenti;
db.student.count().then (ranijeStudenata => {
for(var i = 0; i<studenti.length; i++) {
var ime = studenti[i].imePrezime;
var ind = studenti[i].index;
db.student.findOne({where:{index :studenti[i].index}}).then(stud => {
if (stud == null) {
novi++;
db.student.create({imePrezime:ime, index : ind}).then(noviStudent => {
god.addStudenti(noviStudent);
});
}
else if (stud != null) {
stari++;
god.addStudenti(stud);
}
});
broj++;
}
var brojNovih = broj - ranijeStudenata; //ne koristi se, ali možda hoće
res.set("Content-Type", "application/json");
res.status(200).send(JSON.stringify({message: "Dodano je " + novi + " novih studenata i upisano " + stari + " na godinu " + imeGodine}));
});
});
});
Picture of code
You can use async/await to do counting in a synchronous way.
'use strict';
app.post('/student', async function (req, res) {
var imeGodine = req.body['godina'];
var {studenti} = req.body;
var broj = 0;
var stari = 0;
var novi = 0;
let god = await db.godina.findOne({where: {nazivGod: req.body.godina}});
let ranijeStudenata = await db.student.count(); // ranijeStudenata not used?
for (var i = 0; i < studenti.length; i++) {
var ime = studenti[i].imePrezime;
var ind = studenti[i].index;
let stud = await db.student.findOne({where: {index: studenti[i].index}});
if (stud === null) {
novi++;
let noviStudent = await db.student.create({imePrezime: ime, index: ind});
god.addStudenti(noviStudent);
} else if (stud !== null) {
stari++;
god.addStudenti(stud);
}
broj++;
}
return res.status(200).send({
message: "Dodano je " + novi + " novih studenata i upisano " + stari + " na godinu " + imeGodine
});
});

Async await in node js with readline inside for loop

So I'm unable to force a for loop to wait for the stream to close before performing the next iteration.
It seems streaming data and async/await don't seem to get along (especially in for loops). Possibly one way around it may be to put everything in an infinite while loop (instead of a for loop) and use a POSIX mutex type method (where a flag is set, blocking opening a stream until the flag is reset at when the stream closes, and counters update). But there must be some kind of way to accomplish it with async/await.
Below is some test code:
async function bulk_search(an_array)
{
var name = "";
var found = false;
for(let i = 0; i < 10; i++)
{
for(let j = 0; j < 10; j++)
{
for(let k = 0; k < 10; k++)
{
console.log(i + ", " + j + ", " + k);
file_stream = fs.createReadStream(__dirname + '/a_directory/a_file.csv');
file_stream.on('error', function (err) {
return an_array;
});
csv_file = readline.createInterface({
input: file_stream
});
name = an_array[i][j][k];
found = false;
csv_file.on('line', function (line) {
if(name == line)
{
found = true;
csv_file.close();
}
});
await csv_file.on('close', function() {
console.log("Closing Stream");
if(found == false)
{
an_array[i][j][k] = "";
}
if((i == 9) && (j == 9) && (k == 9))
{
return an_array;
}
});
}
}
}
}

Mongojs find by uuid _id

I am trying to find one record with "monogjs" by _id.
Our _id is a guid (.net).
So I have something like this "80cd95b8-79bf-4025-933b-cabc71fbdc9f" as a string.
Now I tried "monogdb.bsonpure" with a "buffer" specifying the subtype of uuid.
I tried passing it to objectid() but then it tells me it need to be a hex string 12/24.
I just passed it as string but then it just does not return anything
Ok this works
Take "80cd95b8-79bf-4025-933b-cabc71fbdc9f" remove "-"
var Binary = require('mongodb').Binary;
var uuid = require('node-uuid');
var base64data = new Buffer(uuid.parse(param), 'binary').toString('base64');
var bin = new Buffer(base64data, 'base64');
var id = new Binary(bin, Binary.SUBTYPE_UUID_OLD);
So the accepted answer didn't work for me. I found a snippet of code in this github issue to parse a .net guid into a buffer:
guid-parse.js:
'use strict';
// Maps for number <-> hex string conversion
var _byteToHex = [];
var _hexToByte = {};
for (var i = 0; i < 256; i++) {
_byteToHex[i] = (i + 0x100).toString(16).substr(1);
_hexToByte[_byteToHex[i]] = i;
}
// **`parse()` - Parse a UUID into it's component bytes**
function parse(s, buf, offset) {
const i = (buf && offset) || 0;
offset = i;
let ii = 0;
buf = buf || Buffer.alloc(16 + i);
s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
if (ii < 16) { // Don't overflow!
buf[i + ii++] = _hexToByte[oct];
}
});
// Zero out remaining bytes if string was short
while (ii < 16) {
buf[i + ii++] = 0;
}
// Endian-swap hack...
var buf2 = Buffer.from(buf);
buf[offset+0] = buf2[offset+3];
buf[offset+1] = buf2[offset+2];
buf[offset+2] = buf2[offset+1];
buf[offset+3] = buf2[offset+0];
buf[offset+4] = buf2[offset+5];
buf[offset+5] = buf2[offset+4];
buf[offset+6] = buf2[offset+7];
buf[offset+7] = buf2[offset+6];
return buf;
}
// **`unparse()` - Convert UUID byte array (ala parse()) into a string**
function unparse(buf, offset) {
let i = offset || 0;
// Endian-swap hack...
var buf2 = Buffer.from(buf);
buf[i+0] = buf2[i+3];
buf[i+1] = buf2[i+2];
buf[i+2] = buf2[i+1];
buf[i+3] = buf2[i+0];
buf[i+4] = buf2[i+5];
buf[i+5] = buf2[i+4];
buf[i+6] = buf2[i+7];
buf[i+7] = buf2[i+6];
const bth = _byteToHex;
return bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] + '-' +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]] +
bth[buf[i++]] + bth[buf[i++]];
}
module.exports = {
parse,
unparse
};
Then I used it like this:
const mc = require('mongodb').MongoClient;
const { Binary } = require('mongodb').Binary
const guidParse = require("./guid-parse.js");
const NUUID = guidString => {
return new Binary(guidParse.parse(guidString), Binary.SUBTYPE_UUID_OLD);
};
mc.connect('mongodb://localhost:27017/database').then( conn => {
const db = conn.db('database');
return db
.collection('users')
.find({
Guid: NUUID("9EC5955B-E443-456A-A520-8A87DED37EBB")
})
.toArray();
}).then( users => {
console.log(users);
});
And it returned the collection I was looking for!

Resources