scopsy / await-to-js

Async await wrapper for easy error handling without try-catch
http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/
MIT License
3.25k stars 153 forks source link

Using "to", still getting "Unhandled promise rejection", why? #19

Open firepol opened 6 years ago

firepol commented 6 years ago

Hi, I tried your repo in my little crypto project

I use ccxt:

const ccxt = require('ccxt')
let log = require('electron-log')
let to = require('await-to-js')

async withdraw(currency, amount, address, tag = null) {
      let exchange = new ccxt.bitstamp(myApiKey)
      let error, response
      [error, response] = await to(exchange.withdraw(currency, amount, address, tag))
      log.info(error)
      log.info(response)
      return response || error
}

When I call my withdraw function and I try to withdraw 5 ripple (and I know it should generate an error), I still get:

(node:18252) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): TypeError: to is not a function (node:18252) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. (node:18252) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): Error: bitstamp {"status":"error","reason":{"amount":["Ensure this value is greater than or equal to 20."]}}

Ideally I'd like to return either the response or the error.

Ideas why this doesn't work? Looking at your documentation I was expecting this repo to handle the errors. Thanks for any help.

firepol commented 6 years ago

Never mind, I uninstalled your module and just did like this:

[error, response] = await myAsyncFunction(myArg1, myArg2).then(response => {
return [null, response];
).catch(error => [error]);
return response || error

And it works...

I tried also to change variable names and use data and err and still got the same error about unhandled promise. So yeah your module was a cool idea if only it could work for me. For now I use the code I posted in this comment, it only works with that, but not with your to solution...

scopsy commented 6 years ago

@firepol I will try to replicate the issue using 'ccxt' in the next couple of days. Thanks for reporting!

richytong commented 5 years ago

@firepol the reason you're getting to is not a function is because the await-to-js module only has the default export. in your case, if you want to keep using require, you'll need to do

let to = require('await-to-js').default

@scopsy perhaps it is worth adding the module export for people who want to use this with require?

HenriqueSilverio commented 5 years ago

Same error here, using NodeJS 12 with flags.

--experimental-modules --es-module-specifier-resolution=node