【问题标题】:Print Variable Into JSON NodeJS将变量打印到 JSON NodeJS
【发布时间】:2019-12-25 07:05:46
【问题描述】:

我正在使用 NodeJS 开发 API。当我得到未定义的值 打印值。

这是我的代码:

const modelMateris = require("../models/materi");

var Home = {
  getHome: (req, res, next) => {

    const materisAsync = new Promise((resolve, reject) => {
      modelMateris.find({},(err, res) => {
        if(err) reject(err);
        resolve(res);
      });
    });

    var a = materisAsync
      .then(res => console.log(res))
      .catch(res => console.log(err));

    res.send({code:1000, materis:a });
  }
}

module.exports = Home;

我只想将 var A 的输出显示到 RESTAPI 中。那么如何在 NodeJS 中打印呢?

【问题讨论】:

    标签: javascript node.js json rest api


    【解决方案1】:
    materisAsync
        .then(res => {
            console.log(res)
            const a = res
            res.send({code:1000, materis: res});
        })
        .catch(res => console.log(err));
    

    当您使用 then 块时,promise 解析的值将进入 then 块并分配给变量,您可以使用 async await 代替 then 块,如下所示。

    var Home = {
            getHome: async (req, res, next) => {
                try {
                    const materisAsync = new Promise((resolve, reject) => {
                        modelMateris.find({}, (err, res) => {
                            if (err) reject(err);
                            resolve(res);
                        });
                    });
    
                    const a = await materisAsync
                    const b = await secondApicall // like this you can call multiple api
    
                    res.send({ code: 1000, materis: a});
                } catch(error) {
                    console.log(error)
                }
            }
        }
    

    【讨论】:

    • 实际上我想创建来自不同数据库模型的多个 API。所以我声明变量来处理它。顺便说一句,您的代码仍然无法正常工作,因为我使用邮递员运行它
    • 调用多个api可以使用async await,我已经修改了代码,请大家找找。
    猜你喜欢
    • 2018-10-12
    • 2015-06-18
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 2013-04-18
    • 2018-10-18
    相关资源
    最近更新 更多