Erez Erez - 6 months ago 13
Node.js Question

node js function.then in not a function using q

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

Answer

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;
}
Comments