【问题标题】:promise pending while performing CRUD operations even when there's no promise即使没有承诺,在执行 CRUD 操作时承诺未决
【发布时间】:2021-08-12 15:28:21
【问题描述】:

我正在尝试使用电子邮件和密码创建一个注册页面。 我在发布请求时遇到问题。 每当我通过邮递员发帖时,它都会不断发送请求。 并且控制台显示承诺待处理。

function registration()    
{
    app.post('/login', (req, res) => {
       const model = new Model({
            email: req.body.email,
            password: req.body.password
        })
        const result = model.save();
        console.log(result);
    }) 
}
registration();```


//here's the remaing portion

`
const express = require('express');
const app = express();
app.use(express.json());
const mongoose = require('mongoose');
const port = process.env.port || 3000;
app.listen(port, () => console.log(`listening to port ${port}`));

mongoose.connect("mongodb://localhost:27017/Login", { useNewUrlParser: true, useUnifiedTopology: true })
.then(()=>console.log('connected mfs'))
.catch((err) => console.error("error found...", err));

const LoginSchema = new mongoose.Schema({
    email:{type:String, required: true},
    password:{type:String, required :true}
});

const Model = mongoose.model('login', LoginSchema);

【问题讨论】:

    标签: node.js json mongoose postman


    【解决方案1】:

    .save() 函数返回一个承诺

    可能的解决方案

    1- 使用异步/等待

    function registration() {
      app.post('/login', async (req, res) => {
        const model = new Model({
          email: req.body.email,
          password: req.body.password
        })
        const result = await model.save();
        console.log(result);
      })
    }
    

    2- 使用承诺

    function registration() {
      app.post('/login', (req, res) => {
        const model = new Model({
          email: req.body.email,
          password: req.body.password
        })
        model.save().then(result => console.log(result))
      })
    }
    

    3- 使用回调(虽然不推荐)

    您也可以使用.create() 代替new Model({}),然后使用model.save()

    喜欢这个

    1- 异步/等待

    function registration() {
      app.post('/login', async (req, res) => {
        const model = await Model.create({
          email: req.body.email,
          password: req.body.password
        })
        console.log(model)
      })
    }
    

    2- 承诺

    function registration() {
      app.post('/login',  (req, res) => {
        Model.create({
          email: req.body.email,
          password: req.body.password
        })
        .then(model => console.log(model))
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-10
      • 2018-05-25
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      相关资源
      最近更新 更多