Skip to content

attempt

js
_.attempt(func, [args])

尝试调用 func,返回结果或捕获的错误对象。在调用 func 时,将向其提供任何其他参数。

¥Attempts to invoke func, returning either the result or the caught error object. Any additional arguments are provided to func when it's invoked.

新增于

¥Since

3.0.0

参数

¥Arguments

  1. func (函数):要尝试的函数。

    ¥func (Function): The function to attempt.

  2. [args] (...*):用于调用 func 的参数。

    ¥[args] (...)*: The arguments to invoke func with.

返回

¥Returns

(*):返回 func 结果或错误对象。

¥()*: Returns the func result or error object.

示例

¥Example

js
// Avoid throwing errors for invalid selectors.
var elements = _.attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '>_>');

if (_.isError(elements)) {
  elements = [];
}

Lodash v4.17 中文网 - 粤ICP备13048890号