我正在深入研究节点7 async/await功能,并在这样的代码中保持绊脚石
function getQuote() {
let quote = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
return quote;
} …Run Code Online (Sandbox Code Playgroud) ES2017 async/await的一个很好的模式是:
async function () {
try {
var result = await some_promised_value()
} catch (err) {
console.log(`This block would be processed in
a reject() callback with promise patterns
but this is far more intuitive`)
return false // or something less obtuse
}
result = do_something_to_result(result)
return result;
}
Run Code Online (Sandbox Code Playgroud)
能够处理这样的错误非常好.但是我想异步获取一个值,我想保护它不被重新分配(例如:数据库会话),但我仍然想使用async/await模式(纯粹因为我认为它更直观).
以下将不起作用,因为const是块作用域:
async function () {
try {
const result = await get_session()
} catch (err) {
console.log(`This block should catch any
instantiation errors.`)
return false
}
// Can't get at …Run Code Online (Sandbox Code Playgroud) 对于错误报告,我想在我拥有的每个函数的代码周围插入一个try-catch包装器.
所以基本上我想替换
function foo(arg){
bar();
}
Run Code Online (Sandbox Code Playgroud)
...与...
function foo(arg){
try {
bar()
}
catch(e){
customErrorHandler(e)
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将这个通用的try-catch事物应用于所有函数而无需手动编辑所有函数?例如,通过修改Function对象的原型?
编辑
为什么我要尝试捕获我的所有功能:我正在构建一个我在iOS和Android上发布的HTML5应用程序.我可以从我目前的基本javascript错误报告中看出,即使应用程序在我自己的设备上运行良好,其他一些设备上也会出现错误.
我的目标是双重的:每当某人的设备上发生javascript错误时......
工作案例:
当我们调用异步函数并且该函数返回承诺 resolve() 时,异步等待工作正常
不工作的情况:
异步等待不适用于 mongo DB 查询
试过 then(), async/await
我有 2 个 JS 文件。
在 one.js 文件中,我正在导入 functionone.js 中的函数
工作案例:
当 one.js 看起来像
var functiononestatus = transactions.functionone(req.session.email).then((came) => {
console.log(came); // getting `need to be done at first` message
console.log("exec next")
});
Run Code Online (Sandbox Code Playgroud)
当 functionone.js 看起来像
module.exports.functionone = functionone;
async function functionone(email) {
return await new Promise((resolve, reject) => {
resolve('need to be done at first')
});
});
Run Code Online (Sandbox Code Playgroud)
非工作情况(当需要执行 mongo db 查询时):
当 one.js 看起来像
var functiononestatus = …Run Code Online (Sandbox Code Playgroud) async-await ×3
javascript ×3
node.js ×3
asynchronous ×1
es6-promise ×1
mongodb ×1
promise ×1
prototype ×1
try-catch ×1