[英]Why a promise is not always fulfilled, although it has the same parameters (node.js)?
[英]Node.js - Why would a Promise appear to return both fulfilled and rejected?
Node.JS:版本10.16.0
问题:为什么Promise似乎会同时返回已实现和已拒绝?
背景:以下简化的测试服务器旨在连接到MongoDB Atlas数据库。 mongoose.connect()
返回一个承诺。 由于某些原因.then()
.catch()
.then()
和.catch()
语句被触发,并且控制台同时打印“已连接”和“未连接”。 我认为那是不可能的。
"use strict";
const express = require('express');
const mongoose = require('mongoose');
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, 'controllers/.env') });
const app = express();
const PORT = process.env.PORT || 5000;
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true })
.then( console.log('connected') )
.catch( console.log('not connected') );
app.listen(PORT, console.log(`Server started on port ${PORT}`));
then&catch应该接收一个回调函数,您正在调用console.log。
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true })
.then(() => console.log('connected') )
.catch(() => console.log('not connected') );
在promise解决或拒绝之前,您实际上调用了两个console.log()
语句。 这是因为你没有把他们的函数内传递给函数来.then()
和.catch()
相反,你立即调用它们,然后通过他们返回值.then()
和.catch()
请记住,你总是要传递一个函数引用.then()
和.catch()
这样的承诺的基础设施可以调用该函数晚些时候。
实际上,您的代码与此类似:
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true })
.then(undefined)
.catch(undefined);
// these will both get called before the above promise resolves or rejects
console.log('connected');
console.log('not connected')
你叫两个console.log()
在同一时间语句.then()
和.catch()
被调用。
相反,你需要用他们的回调函数里面,你传递给.then()
和.catch()
是这样的:
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true })
.then(() => console.log('connected') )
.catch(() => console.log('not connected') );
或者,也许这在常规函数中更明显:
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true }).then(function() {
console.log('connected');
}).catch(function() {
console.log('not connected');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.