节点服务器以调试模式返回数据,但不以实时模式返回数据

当我在调试模式下运行我的节点服务器,并从get请求执行下面的GET函数时,它在大约500ms内返回我期望的数据。如果我在实时模式下运行服务器并执行相同的操作,则不会得到任何响应。

如果我以类似的方式访问getTime函数,在调试模式下,我会在大约300ms内获得有效数据,但在实时模式下,我会得到一个空字符串。

我有一种感觉,问题出在我如何处理异步,因为调试模式的运行速度比实时模式慢一点,但这也意味着我无法在调试模式下解决这个问题。

var storage = require('../services/storage');

module.exports = {
  get: async function(req, res){
    console.log('request received.');
    let data = await getClientData();      
    let clientData = JSON.parse(data);
    if (clientData){
      console.log('returning data.');
      res.send(clientData);
    }
  }, 
  getTime: async function(req, res){
    console.log('Getting time from storage');
    let data = await getClientData(); 
    let time = JSON.parse(data).time;
    console.log('getTime: ', time);
    res.send(time);
  }
}

async function getClientData(){
  return await storage.get('clientData');
}

存储模块:

if (typeof localStorage === "undefined" 
|| localStorage === null) {
  var LocalStorage = 
    require('node-localstorage').LocalStorage;
  localStorage = new LocalStorage('./scratch');
}

module.exports = {
  get: async function(key){
    try {
      console.log('pulling from storage');
      let data = await localStorage.getItem(key);
      if (data !== null && data !== ''
      && typeof data !== 'undefined') {
        console.log('data has been pulled');
        return data;
      } else {
        return false;
      }
    } catch (error) {
      console.error(
        'Unable to get ' + key + ' from localStorage!'
      );
      console.log(error);
    }
    console.log('the localstorage if statement failed to run');
  },
  set: function(key, value){
    try {
      console.log('Saving to localStorage');
      let objectToStore = {
        data: value,
        time: new Date()
      };
      let stringToStore = 
        JSON.stringify(objectToStore);
      localStorage.setItem(
        key, 
        stringToStore
        );
    } catch (error) {
      console.error(
        'Error while saving to localStorage!'
      );
      console.error(error);
    }
  }
}

我添加了一些控制台语句来帮助跟踪流程,并根据注释进行了一些更改。仍然有同样的问题。根据控制台的输出,看起来getTime函数没有等待存储模块的get函数返回就继续执行了。

调试控制台输出(两个示例都是调用getTime函数):

Getting time from storage
pulling from storage
data has been pulled
getTime:  2018-02-09T14:12:05.141Z

实时控制台输出:

Getting time from storage
pulling from storage
getTime:  undefined

转载请注明出处:http://www.antanetwork.com/article/20230526/2336859.html