本文介绍了如何在node.js中将Express与Promise结合使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我将Promise与Express结合使用.

I am using Promise with Express.

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

当我登录errorsArray时,它是空的,我不知道为什么.我是node.js的新手.预先感谢.

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

推荐答案

尝试以下操作,然后请阅读以下文档 https://www.promisejs.org/了解承诺的工作方式.

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

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();
    });
});

您也可能会遇到其他错误(或者不应该那样做的事情).我只是向您展示Promise的基本用法.

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.

这篇关于如何在node.js中将Express与Promise结合使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:23