CallBack在Node Express JS中不起作用

时间:2017-06-15 22:43:23

标签: javascript node.js express callback request

我正努力做这项工作,但我不能。

此功能位于 router.get功能内。我的前端应用程序让我打电话,我要求其他服务。 在此服务中,我获取有关父文件夹的信息。在此之后我制作一个foreach (localProjects.forEach)来获取信息文件夹,这个回调工作得很好但是当我发送 项目时:localProjects 小时仍在0零。我打印时间,但由于某种原因,时间仍然是零。

request.get('/folders/'+parentFolder+'/folders?descendants=false&project=false', {
    'auth': {
        'bearer': Token
    }
}, function(err, response, body) {
    var folders = JSON.parse(body);
    //console.log(folders);
    folders.data.forEach(function (folder) {
        localProjects.push({id: folder.id, name: folder.title, hours: 0})
    });
    // console.log(localProjects)
    localProjects.forEach(function(folder, index){
        getFolderHours(folder,{start:start, end:end}, function (hours) {
            console.log('Total hrs:'+ hours)
            localProjects[index].hours = hours;
        })
    }); //end localprojects
    console.log('responding')
    res.send({totalHours: totalHours, projects:localProjects});
}); // end request timelog

我的回叫功能如下

var getFolderHours = function (folder,period, callback) {
    request.get('folders/'+folder.id+'/timelogs?trackedDate={"start":"'+period.start+'T00:00:00","end":"'+period.end+'T23:59:59"}',{
        'auth': {
            'bearer':Token
        }
    }, function (err, response, body){
        var timelog = JSON.parse(body);
        var hours = 0 ;
        if (! err){
            console.log('Name:'+ folder.name);
            console.log('Hrs:'+ folder.hours);
            // console.log('Id:'+ folder.id);
            timelog.data.forEach(function (task) {
                console.log('Adding:'+ task.hours);
                hours += task.hours
            });
            callback(hours)
        }
    });
}

1 个答案:

答案 0 :(得分:2)

您的代码无效,因为您在getFolderHours完成执行之前发送请求。这是因为getFolderHours是异步的,所以你必须在localProjects中进行操作才能执行循环结束。

我要做的是将getFolderHours包裹在promise对象中,并在localProjects完成循环后解决所有问题。如果你还不熟悉Promises,我建议你阅读我提供的Promise链接。所以你的代码看起来如下:

request.get('/folders/'+parentFolder+'/folders?descendants=false&project=false', {
    'auth': {
        'bearer': Token
    }
}, function(err, response, body) {
    var folders = JSON.parse(body);
    var localProjectsResolved = [];
    //console.log(folders);
    folders.data.forEach(function (folder) {
        localProjects.push({id: folder.id, name: folder.title, hours: 0})
    });
    // console.log(localProjects)
    localProjects.forEach(function(folder, index){
        var currentFolderHours = getFolderHours(folder,{start:start, end:end}, function (hours) {
            console.log('Total hrs:'+ hours)
            localProjects[index].hours = hours;
        });
        localProjectsResolved.push(currentFolderHours);
    }); //end localprojects
    console.log('responding');
  // resolve all localprojects
  Promise.all(localProjectsResolved).then(function(localProjectResults) {
      // got the results, send the request
      res.send({totalHours: totalHours, projects:localProjectResults});
    });
}); // end request timelog

// wrap getFolderHours in promise
function getFolderHours(folder,period) {
  return new Promise(function(resolve, reject) {
    request.get('folders/'+folder.id+'/timelogs?trackedDate={"start":"'+period.start+'T00:00:00","end":"'+period.end+'T23:59:59"}',{
          'auth': {
              'bearer':Token
          }
      }, function (err, response, body){
          var timelog = JSON.parse(body);
          var hours = 0 ;
          if (!err){
              console.log('Name:'+ folder.name);
              console.log('Hrs:'+ folder.hours);
              // console.log('Id:'+ folder.id);
              timelog.data.forEach(function (task) {
                  console.log('Adding:'+ task.hours);
                  hours += task.hours
              });
              // resolve the number of hours
              resolve(hours);
          } else {
            reject(err);
          }
      });
  });
}