gpt4 book ai didi

javascript - 我收到未处理的 promise 拒绝错误,但无法弄清楚原因

转载 作者:行者123 更新时间:2023-12-03 07:25:48 25 4
gpt4 key购买 nike

const express = require('express');
const cors = require('cors');
const massive = require('massive');
const bodyParser = require('body-parser');
const config = require('../config');

const app = express();

app.use(bodyParser.json());

//massive connection string to database

massive(config.dblink).then(db => {
app.set('db', db)

app.get('db').seed_file().then(res => {
console.log(res)
})
}).catch(err => {
console.log(err)
});

const port = 3001;
app.listen(port, () => {console.log(`the server is listening on ${port}`)})

我收到以下错误:

(node:173676) UnhandledPromiseRejectionWarning: Unhandled promise rejection 
(rejection id: 2): error: syntax error at or near "{"
(node:173676) [DEP0018] DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.

我还没弄清楚哪里出了问题。我看过多个不同的例子,但看不出问题所在。在我的 seed_file promise 之后,我有一个 .catch

有什么想法吗?

最佳答案

I'm getting an Unhandled Promise Rejection error but can't figure out why

您收到此警告是因为您有未处理的 promise 拒绝 :)。外部 catch() 方法不处理嵌套的 promise 拒绝,因此两个选项可能是:

1) 在嵌套的 promise 上使用 return,它将被外部 catch() 捕获:

massive(config.dblink).then(db => {
app.set('db', db)
return app.get('db').seed_file().then(res => {
console.log(res)
});
}).catch(err => console.log(err) });

2) 使用内部 catch() 以不同方式处理嵌套拒绝:

massive(config.dblink).then(db => {
app.set('db', db)
app.get('db').seed_file().then(res => {
console.log(res)
}).catch(err => console.log(err) });
}).catch(err => console.log(err) });

演示:

function doPromise(someText, flag) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
flag ? resolve(someText) : reject(someText);
}, 500);
});
}

/* The following sample demostrates unhandled rejection */
doPromise('this will resolve', true).then(function(res1) {
console.log(res1);
doPromise('this is unhandled promise rejection', false).then(function(res2) {
console.log(res2);
});
});

/* The following sample demostrates handling nested promise rejection like explained in point 1) */
doPromise('1) this will resolve', true).then(function(res1) {
console.log(res1);
return doPromise('1) nested rejection catched from outside', false);
}).catch(err => console.log(err));


/* The following sample demostrates handling nested promise rejection like explained in point 2) */
doPromise('2) this will resolve', true).then(function(res1) {
console.log(res1);
doPromise('2) nested rejection catched from inside', false).catch(err => console.log(err));
}).catch(err => console.log(err));

关于javascript - 我收到未处理的 promise 拒绝错误,但无法弄清楚原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46994776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com