相关疑难解决方法(0)

使用async/await尝试/捕获块

我正在深入研究节点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)

node.js async-await ecmascript-2017

100
推荐指数
5
解决办法
11万
查看次数

正确尝试...使用Async/Await捕获语法

我喜欢Async/Await在Typescript等中提供的新功能的平坦性.但是,我不确定我喜欢这样一个事实,即我必须awaittry...catch块的外部声明变量才能在以后使用它.像这样:

let createdUser
try {
    createdUser = await this.User.create(userInfo)
} catch (error) {
    console.error(error)
}

console.log(createdUser)
// business
// logic
// goes
// here
Run Code Online (Sandbox Code Playgroud)

如果我错了,请纠正我,但似乎最好不要在机构中放置多行业务逻辑try,所以我只留下createdUser在块外声明,在块中分配它的替代方案,以及然后用它.

在这种情况下,最佳做法是什么?

javascript try-catch promise async-await ecmascript-2017

49
推荐指数
3
解决办法
2万
查看次数

有没有办法将await/async try/catch块包装到每个函数中?

所以我正在使用express.js并考虑使用async/await与节点7.有没有办法我仍然可以捕获错误但摆脱try/catch块?也许是函数包装器?我不确定这将如何实际执行函数的代码并调用next(err).

exports.index = async function(req, res, next) {
  try {
    let user = await User.findOne().exec();

    res.status(200).json(user);
  } catch(err) {
    next(err);
  }
}
Run Code Online (Sandbox Code Playgroud)

像这样......?

function example() {
   // Implements try/catch block and then handles error.
}

exports.index = async example(req, res, next) {
  let user = await User.findOne().exec();
  res.status(200).json(user);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

更类似的东西:

var wrapper = function(f) {
    return function() {
        try {
            f.apply(this, arguments);
        } catch(e) {
            customErrorHandler(e)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这会以某种方式处理try/catch块但不起作用:

exports.index = wrapper(async example(req, res, next) { …
Run Code Online (Sandbox Code Playgroud)

javascript express async-await ecmascript-2017

11
推荐指数
1
解决办法
3902
查看次数