Node.js - 为什么 Promise 在 return 看来既实现又被拒绝?

Node.js - Why would a Promise appear to return both fulfilled and rejected?

Node.JS: 版本 10.16.0

问题: 为什么一个 Promise 在 return 看来既实现又被拒绝?

背景: 以下简化的测试服务器旨在连接到 MongoDB Atlas 数据库。 mongoose.connect() return 是一个承诺。由于某种原因,.then().catch() 语句被触发并且控制台同时打印 'connected' 和 'not connected'。我不认为这是可能的。

"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') );

你实际上在承诺解决或拒绝之前调用了两个 console.log() 语句。这是因为您没有将它们放在函数中并将该函数传递给 .then().catch()。相反,您会立即调用它们,然后将它们的 return 值传递给 .then().catch()。请记住,您始终必须将函数引用传递给 .then().catch(),以便 promise 基础结构可以稍后调用该函数。

实际上,您的代码与此类似:

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')

您在调用 .then().catch() 的同时调用了两个 console.log() 语句。


相反,您需要将它们包装在传递给 .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');
});