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.
我无法弄清楚出了什么问题。我看了几个不同的例子,但看不出问题。我的.catch
承诺后我有一个seed_file
。
有什么想法吗?
答案 0 :(得分:4)
我收到了未处理的承诺拒绝错误,但无法弄清楚 为什么
您收到此警告是因为您有未处理的拒绝承诺 :)。外部catch()
方法不处理嵌套的承诺拒绝,因此有两个选项可以:
1)在嵌套的承诺上使用返回,它将从外部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));