Huy*_*ang 4 node.js async-await loopbackjs es6-promise
我收到一个错误,说
(node:27301) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Callback was already called.
Run Code Online (Sandbox Code Playgroud)
根据我对在 await 和 Mozilla 描述中拒绝承诺的理解:
如果 Promise 被拒绝,则 await 表达式会抛出被拒绝的值。
我拒绝了我的 Promise 周围的回调中的错误,如下所示:
Airport.nearbyAirports = async (location, cb) => {
let airports
try {
airports = await new Promise((resolve, reject) => {
Airport.find({
// code
}, (err, results) => {
if (err)
reject(err) // Reject here
else
resolve(results)
})
})
} catch (err) { // Catch here
cb(err, null)
return
}
if (!airports.empty)
cb(null, airports)
}
Run Code Online (Sandbox Code Playgroud)
我的问题是
catch声明应该消除此错误。return声明catch,所以永远不应该调用两者。问题实际上是我的框架(LoopbackJS),而不是我的函数。显然在撰写本文时,不支持使用承诺:
https://loopback.io/doc/en/lb3/Using-promises.html#setup
这意味着我什至不能await在我的函数中使用,因为远程方法将我的函数包装在其他地方,所以async总是无法处理。我最终回到了基于 Promise 的内部代码实现:
Airport.nearbyAirports = (location, cb) => {
const settings = Airport.dataSource.settings
const db = DB(settings)
let airports
NAME_OF_QUERY().then((res) => {
cb(null, res)
}).catch((err) => {
cb(err, null)
})
Run Code Online (Sandbox Code Playgroud)