2017-10-28 65 views
0
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承諾後,我有一個.catch

有什麼想法?

+0

右下方'的console.log(RES)'你有一個額外'})'。刪除,你應該是好的 –

+0

@MarkDodds不是這樣,只是代碼格式不正確 – codtex

回答

4

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

,因爲你有未處理的承諾拒絕您收到此警告:)。您嵌套承諾

1)使用回報,它會從外catch()被抓:外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));

相關問題