【问题标题】:Async Nested Callbacks using Express + Request node module in a MVC structure在 MVC 结构中使用 Express + Request 节点模块的异步嵌套回调
【发布时间】:2017-10-12 12:03:43
【问题描述】:

我正在为使用 Node Request 将模型文件中的一些数据传回控制器的最后一步感到苦恼。

我已经成功地从我的模型文件中设置了一个回调,它使用请求从外部源加载 JSON。

我的控制器可以访问它,但我认为我仍然需要在最后一步中使用某种嵌套的第二个回调,因为我希望变量 pageJSON 包含 JSON 对象并且无法完全弄清楚如何。

我想我在这方面有点碰壁了,如果能以新的眼光看待这个问题,我将不胜感激!感觉就像我在这一点上错过了一些非常简单的东西(我希望!)

我的模型文件:

module.exports = function (config, callback) {
  const request = require('request');
  const options = {
    'url' :  config.urls.page,
    'json' : true,
    'auth': {
      'user': config.auth.username,
      'pass': config.auth.password
    }
  };

  request(options, (error, response, body) => {
    if (error) {
      console.log(error);
    }
    callback(body);
  });
}

我的控制器文件:

const express = require('express');
const router = express.Router();
const app = express();
const config = require('../config');
const page = require('../models/page');

let pageJSON = page(config, (json) => {
  console.log(json); // This shows the JSON structure in console
  return json;
});

console.log(pageJSON); // Undefined

// Manipulate JSON and pass request view accordingly using Express

【问题讨论】:

  • 你不能把剩下的代码放在控制器文件的回调中吗?
  • 我不熟悉 node-request 但我注意到您的 page 函数没有返回任何内容。所以pageJSON = page(...)一定是错的
  • 看起来 pageJSON 正在以异步方式返回一个值。您可能需要使用返回的 json 调用另一个函数,或者将函数作为回调传递给 pageJSON,以便在返回 json 时调用。
  • 显然 json 操作必须发生在你的回调中

标签: javascript node.js express model-view-controller node-request


【解决方案1】:

您必须在控制器回调中处理 json 操作(或从中调用另一个回调):

let pageJSON = page(config, (json) => {
   console.log(json); // This shows the JSON structure in console
   processJSON(json);
});

pageJSONundefined,因为您的模型没有返回任何内容。

【讨论】:

    猜你喜欢
    • 2015-10-28
    • 2016-12-26
    • 2023-04-02
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2016-06-01
    • 2016-10-23
    • 2018-03-05
    相关资源
    最近更新 更多