Attempt to execute a function and return the result or error. Returns a Promise that resolves to a tuple where:
Only applicable to asynchronous execution functions
尝试执行函数并返回结果或错误。返回一个解析为元组的 Promise,其中:
仅适用于异步执行函数
The asynchronous function to execute - 要执行的异步函数
The arguments to pass to the function - 要传递给函数的参数
const [error, result] = await attemptAsync(() => Promise.resolve(12)) // [null, 12]const [error, result] = await attemptAsync(() => { Promise.reject(new Error('error')) }) // [Error, null] Copy
const [error, result] = await attemptAsync(() => Promise.resolve(12)) // [null, 12]const [error, result] = await attemptAsync(() => { Promise.reject(new Error('error')) }) // [Error, null]
const add = (a, b) => Promise.resolve(a + b)const [error, result] = await attemptAsync(add, 1, 2) // [null, 3]// orconst [error, result] = await attemptAsync(async() => await add(1, 2)) // [null, 3] Copy
const add = (a, b) => Promise.resolve(a + b)const [error, result] = await attemptAsync(add, 1, 2) // [null, 3]// orconst [error, result] = await attemptAsync(async() => await add(1, 2)) // [null, 3]
Attempt to execute a function and return the result or error. Returns a Promise that resolves to a tuple where:
Only applicable to asynchronous execution functions
尝试执行函数并返回结果或错误。返回一个解析为元组的 Promise,其中:
仅适用于异步执行函数