2021年1月17日星期日

Node: Unhandled promise rejection

I'm working through a js/node workshop on async programming called promise-it-wont-hurt. I have the following exercise:

  • Some invalid JSON will be available on process.argv[2].
  • Build a function called parsePromised that creates a promise,performs
  • JSON.parse in a try/catch block, and fulfills or rejects the promise depending on whether an error is thrown. Note: your function should synchronously return the promise!
  • Build a sequence of steps like the ones shown above that catchesany thrown errors and logs them to the console.

my answer:

function parsePromised(json) {    return new Promise(function(resolve, reject){        resolve( JSON.parse(json) ),        reject(throwError)    });    }    parsePromised(process.argv[2]).then(console.log);  

The stack trace is:

(node:3499) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token u in JSON at position 0  at JSON.parse (<anonymous>)  at /home/optionhomes11/nodeprojects/promise-shop/test.js:184:21  at new Promise (<anonymous>)  at parsePromised (/home/optionhomes11/nodeprojects/promise-shop/test.js:183:10)  

and the exercise result gives:

Your solution to Throw an error didn't pass. Try again!  

Any idea how to get this working?

https://stackoverflow.com/questions/65768259/node-unhandled-promise-rejection January 18, 2021 at 10:58AM

没有评论:

发表评论