node js function.then in not function using q

时间:2016-06-02 13:03:15

标签: node.js promise q

你好,所以有线我试图做异步功能但是当我使用它时我得到错误

使用q 在包json上 "q": "^1.4.1"

TypeError: helper.setNextUserNewsAction(...).then is not a function

这是我的帮手

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

当我在控制器中调用此函数时,它会向我发送错误

var helper = require('../helpers/playlist');
helper.setNextUserNewsAction(15).then(function(action){
     console.log(action);
},function(err){ 
     console.log(err);
});

我也尝试用try和catch做同样的错误 好吧,这不是第一次或20我使用q 希望有人可以提供帮助

1 个答案:

答案 0 :(得分:1)

问题是你从for循环中返回了一些内容:

for (var i = 0, j = minutesToSet; j <= 60; i += minutesToSet, j += minutesToSet) {
    if (minutes > i && minutes < j)
        return newMinutesToSet = (i % 60);
}

因此setNextUserNewsAction函数未返回承诺,因此没有.then()

试试这个:

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