Elegant deviation handling on `await`ed Javascript Promise

Great template with ES2017 async / await:

async function () {
  try {
    var result = await some_promised_value()
  } catch (err) {
    console.log(`This block would be processed in
      a reject() callback with promise patterns
      but this is far more intuitive`)
    return false // or something less obtuse
  }
  result = do_something_to_result(result)
  return result;
}

The ability to deal with such errors is very good. But I will say that I want to asynchronously get a value that I would like to protect against reassignment (for example, a database session), but I still want to use the async / await pattern (purely because I think it is much more intuitive).

The following actions will not work because const is a block scope:

async function () {
  try {
    const result = await get_session()
  } catch (err) {
    console.log(`This block should catch any
      instantiation errors.`)
    return false
  }
  // Can't get at result here because it is block scoped.
}

, try, , . (, , , , , , . , - - , .)

, , . Promises . var const let. .

[question]: try/catch await/async ? , , try/catch. , try/catch , return try/catch, async/await, - .

- const x = await y() catch (err) const x = await y() || fail , .

UPDATE: @jmar777 , :

const x = await y().catch(() => {/*handle errors here*/})

, , . return, . .

.

let ( jmar777) , , .

+4
1

const. const , , :

const . , , , , . , , , . (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)

, , result try/catch:

async function () {
  let result;

  try {
    result = await get_session()
  } catch (err) {
    console.log(`This block should catch any
      instantiation errors.`)
  }

  // do whatever else you need with result here...
}

, try/catch. :

async function () {
  const result = await get_session().catch(someRejectionHandler); 

  // do whatever else you need with result here...
}

, , get_session() , result . , , , .

+4

Source: https://habr.com/ru/post/1667093/


All Articles