Lodash: Async version of _.attempt

Created on 28 Mar 2016  路  3Comments  路  Source: lodash/lodash

Since ES7 would probably contain async/await pattern it would be nice to have a version on _.attempt that would work with it. For example

const response = await _.attemptAsync(makeRequest, requestOptions)
if (_(response).isError()) return console.error('Fail to request:', response)
const responseData = response.map(......)

In practice this means that _.attemptAsync returns a Promise that will never be rejected and resolve with either result or error

I understand that it may be a little bit early for such feature, but may be you may consider it for future versions

enhancement votes needed

Most helpful comment

Ended up writing this locally for a project.

async function attemptAsync (func, ...args)  {
  try {
    return await func(...args)
  } catch(e) {
    return e
  }
}

// Usage
const dataOrError = await attemptAsync(async () => { ... })

All 3 comments

For async helpers I defer to async.
We'll keep an eye on the popularity of the request.

Ended up writing this locally for a project.

async function attemptAsync (func, ...args)  {
  try {
    return await func(...args)
  } catch(e) {
    return e
  }
}

// Usage
const dataOrError = await attemptAsync(async () => { ... })

@jdalton still not interested in adding this to lodash ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

erykpiast picture erykpiast  路  3Comments

jwngr picture jwngr  路  3Comments

satrong picture satrong  路  3Comments

JoMas971 picture JoMas971  路  3Comments

jasonkarns picture jasonkarns  路  3Comments