【问题标题】:Module exports promise result on fulfilled模块导出承诺结果已完成
【发布时间】:2018-08-12 06:19:18
【问题描述】:

节点-v 8.9.3

我有自己的模块,它是另一个模块的一部分,如下所示:

module.js

function module(name) {
    request(['arr_result1', 'arr_result2', 'arr_result3'], {params, name}) //it's not actual request, I just rename it, 'name' is the same as function
        .then(response => {
            let data = [];
            data.name = response.data.arr_result1;
            data.guild = response.data.arr_result2;
            data.check_sum = 0;
            for (let i = 0; i < 3; i++) {
                data.check_sum += adler32.sum(new Buffer((response.data.arr_result3)));
            }
            return (data);
        })
        .then(data => {
            if (data.arr_result2 === undefined) {
                data.arr_result2 = 'TEST';
            } else {
                data.arr_result2 = data.arr_result2;
            }
            //other logic 
            console.log(data);
            return data;
        })
        .catch(function (error) {
            console.log(error )
        });
    }

module.exports = module;

我想通过以下方式将此“请求承诺”的结果(来自 console.log 的“数据”)导入另一个文件(如 app.js):

app.js

const module = require("./module");

我的模块工作正常,(console.log 打印我想要的确切数据)但我无法通过 import 或 require 从另一个 *.js 访问数据: 在这种情况下:

let data = module('name');
console.log(data);

我收到的数据 - 未完成(因为请求是承诺但尚未完成,对吗?)

但是当我尝试这样做时:

module('name').then((data=> {console.log(data)});

我有错误:TypeError: Cannot read property 'then' of undefined

那么我做错了什么,我应该如何重写它? 实际上它是如何工作的,我指向/定义函数('name'),并且模块通过异步请求提供必要的数据。然后将其“返回”到 app.js P.S.实际上我重命名了代码中的每个变量以便更好地解释。在我自己的情况下,它不是一个“请求”,我的模块绝对有另一个名称。

更新

是的,我已经尝试过

function module(name) {
    return request(['arr_result1', 'arr_result2', 'arr_result3'], {params, name})

“数据”打印正常,但为什么这段代码不能正常工作?

module('name').then(data => {
    console.log(data); //prints succesfully
    mongoose_schema-DB.create({data});
});

(node:17964) UnhandledPromiseRejectionWarning: UnhandledPromiseRejection (rejection id: 1): ValidationError: **这里是验证错误,就像根本没有数据一样,但是console.log将它的数据集打印为'ok'[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。将来,未处理的 Promise 拒绝将使用非零退出代码终止 Node.js 进程。

这里是 mongoose_schema-DB 代码:

让 mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/dma', { useMongoClient: true });
mongoose.Promise = global.Promise;
//schema itself
let mongoose_schema-DB= mongoose.model('mongoose_schema-DB', schema);
module.exports = mongoose_schema-DB;

或 Express 中的这一部分

app.all('/item', function (req, res, next) {
   module('name').then(data => {
        mongooseDB_schema-DB.create({data});
    });
  },function (err, res) {
    if (err) return handleError(err);
    console.log(res);
  });
  next();
});

更新

最有趣的部分是,这段代码运行良好,而不是简单的 mongooseDB_schema-DB.create({data})

module(name).then(data => {
    mongooseDB_schema-DB.create({
        field1: data.1,
        field2: data.2,
        field3: data.3,
        field4: data.4,
        field5: data.5,
        field6: data.6,
    });
});

我正在检查它的 Express 版本...

我只是用回调重写 express 版本,而不是 .catch。不知道如何,但它工作正常。感谢所有 @Bergi 和 @Keith 提供了 nessasry 支持!

【问题讨论】:

  • return request...... 不要忘记回报你的承诺。
  • 哦,是的,我没有注意到,但我已经测试过了,它不会工作。相信我。
  • 实际上它现在正在工作,嗯。在明确的 *.js 文件中。但是当我使用与返回相同的代码时,我无法立即将其重写为 MongoDBm:module('name').then(data => { mongooseDB.create(data) });

标签: javascript node.js mongoose promise async-await


【解决方案1】:

是的,这是一个承诺,您需要像您尝试过的那样使用 .then 等待它,但您还需要从您的 module 函数中 return 那个承诺!

function module(name) {
    return request(['arr_result1', 'arr_result2', 'arr_result3'], {params, name})
//  ^^^^^^
    .then(…)
    .then(…)
    .catch(…);
}

您可能还想省略 catch 并让模块的调用者处理错误,而不是接收 undefined 处理程序结果。

【讨论】:

  • 是的,它返回“数据”变量很好,但为什么这段代码不起作用? --几秒钟内更新
  • 我刚刚修复它,非常感谢,猜想问题是错误处理不当。不是 request-promise 本身或 mongo 验证。
猜你喜欢
  • 2017-10-13
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 2020-03-18
  • 2018-02-13
  • 2020-01-15
  • 2019-06-01
  • 1970-01-01
相关资源
最近更新 更多