如何在node.js中使用Promise和express?

时间:2022-03-31 18:28:06

I am using Promise with Express.

我正在使用Promise和Express。

router.post('/Registration', function(req, res) {
  var Promise = require('promise');
  var errorsArr = [];
  function username() {
    console.log("agyaaa");
    return new Promise(function(resolve, reject) {
      User.findOne({ username: req.body.username }, function(err, user) {
        if(err) {
          reject(err)
        } else {
          console.log("yaha b agyaaa");
          errorsArr.push({ msg: "Username already been taken." });
          resolve(errorsArr);
        }
      });
    });
  }
  var username = username();
  console.log(errorsArr);
});

When I log errorsArray, it is empty and I don't know why. I am new in node.js. Thanks in advance.

当我记录errorsArray时,它是空的,我不知道为什么。我是node.js的新手。提前致谢。

3 个解决方案

#1


12  

Try the following, and after please read the following document https://www.promisejs.org/ to understand how the promises work.

请尝试以下操作,之后请阅读以下文档https://www.promisejs.org/以了解promises的工作原理。

var Promise = require('promise');
router.post('/Registration',function(req,res,next) {
    function username() {
        console.log("agyaaa");
        return new Promise(function(resolve,reject) {
            User.findOne({"username":req.body.username}, function(err,user) {
                if (err) {
                    reject(err)
                } else {
                    console.log("yaha b agyaaa");
                    var errorsArr = [];
                    errorsArr.push({"msg":"Username already been taken."});
                    resolve(errorsArr);
                }

            });
        });
    }
    username().then(function(data) {
        console.log(data);
        next();
    });
});

You can have other errors also (or things that shouldn't be done that way). I'm only showing you the basic use of a Promise.

您也可能有其他错误(或不应该以这种方式完成的事情)。我只向你展示了Promise的基本用法。

#2


1  

router.post('/Registration', function(req, res) {
    return User
        .findOne({ username: req.body.username })
        .then((user) => {
            if (user) {
                return console.log({ msg:"Username already been taken" });
            }
            return console.log({ msg: "Username available." });
        })
        .catch((err)=>{
            return console.error(err);
        });
});

you can write a clean code like this. Promise is a global variable available you don't need to require it.

你可以写一个像这样的干净代码。 Promise是一个全局变量,您不需要它。

#3


0  

Before using promises, you should understand the nature of asynchronous functions and call-backs. In this example when express calls your function(req, res) the req object comes from an HTTP request, and you need to give back some data through the res parameter like this:

在使用promises之前,您应该了解异步函数和回调的本质。在此示例中,当express调用您的函数(req,res)时,req对象来自HTTP请求,您需要通过res参数返回一些数据,如下所示:

errorsArr.push({"msg":"Username already been taken."})
res.json({errors: errorsArr})

#1


12  

Try the following, and after please read the following document https://www.promisejs.org/ to understand how the promises work.

请尝试以下操作,之后请阅读以下文档https://www.promisejs.org/以了解promises的工作原理。

var Promise = require('promise');
router.post('/Registration',function(req,res,next) {
    function username() {
        console.log("agyaaa");
        return new Promise(function(resolve,reject) {
            User.findOne({"username":req.body.username}, function(err,user) {
                if (err) {
                    reject(err)
                } else {
                    console.log("yaha b agyaaa");
                    var errorsArr = [];
                    errorsArr.push({"msg":"Username already been taken."});
                    resolve(errorsArr);
                }

            });
        });
    }
    username().then(function(data) {
        console.log(data);
        next();
    });
});

You can have other errors also (or things that shouldn't be done that way). I'm only showing you the basic use of a Promise.

您也可能有其他错误(或不应该以这种方式完成的事情)。我只向你展示了Promise的基本用法。

#2


1  

router.post('/Registration', function(req, res) {
    return User
        .findOne({ username: req.body.username })
        .then((user) => {
            if (user) {
                return console.log({ msg:"Username already been taken" });
            }
            return console.log({ msg: "Username available." });
        })
        .catch((err)=>{
            return console.error(err);
        });
});

you can write a clean code like this. Promise is a global variable available you don't need to require it.

你可以写一个像这样的干净代码。 Promise是一个全局变量,您不需要它。

#3


0  

Before using promises, you should understand the nature of asynchronous functions and call-backs. In this example when express calls your function(req, res) the req object comes from an HTTP request, and you need to give back some data through the res parameter like this:

在使用promises之前,您应该了解异步函数和回调的本质。在此示例中,当express调用您的函数(req,res)时,req对象来自HTTP请求,您需要通过res参数返回一些数据,如下所示:

errorsArr.push({"msg":"Username already been taken."})
res.json({errors: errorsArr})