logo
Tags down

shadow

How to structure try/catch with async/await?


By : S_P Singh
Date : October 17 2020, 06:10 AM
Any of those help Avoid vexing exceptions by overriding the validateStatus callback. If a 401 status code is an expected outcome, then treat it like one and allow other unexpected status codes to throw as normal:
code :
const response = await axios.put(url, {}, {
  validateStatus (status) {
    return [200, 401].includes(status);
  }
});

switch (response.status) {
case 200:
  MicroService.action(data);
  break;
case 401:
  MicroService.otherAction(data);
  break;
}
const response = await axios.put(url, {}, {
  validateStatus () {
    return true;
  }
});

switch (response.status) {
case 200:
  MicroService.action(data);
  break;
case 401:
  MicroService.otherAction(data);
  break;
default:
  console.error(`The server returned an unexpected ${response.status} error upon attempting to hit ${url}`);
  break;
}


Share : facebook icon twitter icon

Learning C#'s async/await/Task structure; code hangs at await?


By : suvendu
Date : March 29 2020, 07:55 AM
wish of those help You haven't actually run any Task. So you're waiting on something that will never complete.
To fix your code exactly as it is, you can do this:
code :
private Foo RunExecute(out Task<Foo> task, bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        task = Task.Run(() => makeFoo());
        outputFoo = null;
    }
    else
    {
        task = null;
        outputFoo = makeFoo();
    }

    return outputFoo;
}
private Foo RunExecute(out Task<Foo> task, bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        task = makeFooAsync();
        outputFoo = null;
    }
    else
    {
        task = null;
        outputFoo = makeFoo();
    }

    return outputFoo;
}

async Task<Foo> makeFooAsync()
{
    await Task.Delay(3000);
    return new Foo();
}
private Task<Foo> RunExecute(bool async = false)
{
    Foo outputFoo;

    if(async)
    {
        return makeFooAsync();
    }
    else
    {
        return Task.FromResult(makeFoo());
    }
}

Can I catch an error from async without using await?


By : user3750368
Date : March 29 2020, 07:55 AM
Does that help Dealing with unhandled rejected native promises (and async/await uses native promises) is a feature supported now in V8. It's used in the latest Chrome to output debugging information when a rejected promise is unhandled; try the following at the Babel REPL:
code :
async function executor() {
  console.log("execute");
}

async function doStuff() {
  console.log("do stuff");
  throw new Error("omg");
}

function handleException() {
  console.error("Exception handled");
}

(async function() {
  try {
      await executor();
      doStuff();
  } catch(e) {
      handleException();
  }
})()
process.on('unhandledRejection', function(reason, p) {
    console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
    // application specific logging, throwing an error, or other logic here
});

Async / Await JS Catch not working in try/catch


By : Brian Mesa
Date : March 29 2020, 07:55 AM
like below fixes the issue I have the bit of javascript below. Using async/await in our ES6 project. I have noticed that now all of a sudden a 404 response code isn't hitting the catch. In fact the .json() is also throwing a console error but still not hitting the catch. I would expect any error in the try to immediately throw and go to the catch block of code. , If the json() method is asynchronous, you should add one more await:
code :
async getDash(projectId, projectUserId) {
  try {
    const events = await (await this.apiHttp
      .fetch(`${projectId}/users/${projectUserId}/participant-event-dash`)).json();
    return events;
  } catch (e) {
    // fail back to local (dev testing)
    return await (await this.http
      .fetch(`${this.appConfig.url}dist/api/query/json/partic-event-dash.json`)).json();
  }
}

Promise (then - catch) or Async / Await (with Try-Catch) for exceptions control


By : Ander
Date : March 29 2020, 07:55 AM
like below fixes the issue Since you don't ask a very specific question, I'll give you some comments and alternatives on your code. But first a few points:
Programming with async and await is optional. When to use it is partly opinion and partly depends upon exactly what you're doing. If you have only a single asynchronous operation that's part of your code flow, then there's generally no particular the reasons to use await are less compelling as a simple .then() and .catch() will be similar in complexity to the try/catch.
code :
       const post = await newPost.save();

        if (!post) {
            return res.status(422).json({
                errors: 'Error'
            });
        }
const { validationResult } = require('express-validator');
const Post = require('../models/post');

module.exports = {

    //HTTP POST Method

    createPost: (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(422).json({
                errors: errors.array()[0].msg
            });
        }

        const { title, content, imageUrl } = req.body;

        const newPost = new Post({
            title,
            content,
            imageUrl
        });

        newPost.save().then(post => {
            res.status(201).json({
                message: 'Post created successfully!',
                post: {
                    title: title,
                    content: content,
                    image: imageUrl,
                }
            });
        }).catch(err => {
            res.status(500).json({
                errors: 'Error'
            });
        });
    }
}

fetch and async/await without try/catch


By : user3325080
Date : March 29 2020, 07:55 AM
will be helpful for those in need I'm trying to get async await to work without try/catch , This is what I got to work:
code :
  return fetch(url, options)
    .then(async res => {
      if (!res.ok) {
        const err = await res.json()
        throw err.message || res.statusText
      }

      return res.json()
    })
    .catch(err => {
      throw new Error(err)
    })
        const response = await myFetch('/forgot', {
            email
        }, {
            headers: {
                'x-contact': 'hello@puump.com'
            }
        }).catch(err => {
            msg = err.message;
            return;
        });

        if (response) {
            push('/');
        }
Related Posts Related Posts :
  • How can I use function chaining with dates in JavaScript?
  • What is the difference between "delete" and "Reflect.deleteProperty()"
  • How to get attributes of individual elements in jquery array
  • Why do I get different results with "=" vs. "===" in javascript with Conditional (Ternary) Operators
  • I am trying to hold value of document.getElementById("image").src=UserInput +".gif"
  • Array being pushed into another array isn't displaying
  • Is there a React.js NPM module or any other solution for image/object mutli-selection?
  • 80% Javascript Solution for Flags in Codility
  • I want to display background while scrolling down
  • RegEx for matching text between two tags
  • Does having a lot of inner 'helper' functions inside a functional stateless react component will result in worse perform
  • How to submit a form through a button outside the form?
  • ESLint: Use callback in setState when referencing the previous state
  • How to parse state from one component to another in my example?
  • Visible Html select option showing under hidden items
  • Create SVG circle using path with 6 segments
  • Getting error while reading from a text file
  • Read a value from JSON Array without entity
  • Checkbox check or uncheck value null
  • Displaying multiple slider values to users
  • Am doing the destructing right?
  • VueJS data-bind object styling not working
  • Combine array and object destructuring
  • Execution skips promise statements
  • sort an array of objects leaving first field
  • how to highlight table cells in a certain way when hover over
  • Problems when using Chosen Selectors in external helper functions
  • Need to merge two objects together that each have an array to the matching IDs
  • How to get previous 6 months date from current date in javascript
  • how to get object value only without mentioning key from array list using ngFor in angular 7
  • Plugging into on_page_change events in testcafe
  • WithStore: Cannot read property 'state' of undefined (pure-react-carousel)
  • fullcalendar event info in modal popup
  • How do i reduce time complexity of this code
  • Deep comparing object props in React not working as expected
  • JavaScript method to remove case insensitive duplicates from string/Numbers
  • When to use parentheses after function name call (es6)
  • Convert list of Objects when the levels are given in an array
  • template variable always undefined ngOnChanges
  • RegEx for matching the first word
  • Render different au-target-id in aurelia repeat
  • Why does the function start before the button is pressed?
  • where can I vote for changes to javascript?
  • Change the digit format pagination in the slider
  • Hover/focus state activated initially on page load
  • Why do my normal sync codelines, works like async?
  • How to prevent or disable Bootstrap 4 popover auto positioning behavior (Self adjusting behavior)
  • What is the meaning of ({})?
  • How do I make a link to a property if the property is yet to be declared? (In a Class)
  • Getting Promise as return value inside FlatList React-native
  • Why can't you access JSON directly from the response in Fetch API?
  • How to grab value out of this nested array
  • function is not returning any value
  • "Cannot read property 'map' of undefined (React.js)"
  • How do I extract the contents of a specific json within the html?
  • How do I assign a src attribute to the background-image of another element?
  • How to access a public method from a wrapped Component using TypeScript?
  • Errors while looping through the objects
  • How to fix "TypeError: fsevents is not a constructor" react error
  • Invalid JSON characters after processing JSON file in Vue.js
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk