Nested Try/Catch, Async/Await calls - javascript

I'm trying to await an axios post request within a asynchronous catch block. Nothing is being returned from the post request. Is it because I can't use await within a catch block?
Code looks something like:
async function saveData() {
console.log("Saving data");
}
async function doStuff(){
try{
const result = await Axios.get('http://localhost/blah');
return result;
} catch(err) {
if(err.response.status === 400) {
const otherResult = await Axios.post('http://localhost/postaddress');
await saveData();
}
}
}
I've googled around for await within catch block and could only find stuff for C# updating their version to support this. Does Javascript support/not support this? If so why am I not getting anything back from the post request. Thanks!

It seems like you are not using (for return) the variable otherResult that you defined as the result of the axios POST.
Have you tried doing:
async function doStuff(){
try{
const result = await Axios.get('http://localhost/blah');
return result;
} catch(err) {
if(err.response.status === 400) {
const otherResult = await Axios.post('http://localhost/postaddress');
await saveData();
return otherResult; // <--- This line
// return otherResult.response; // If you need the POST response
// return otherResult.data; // If you need the POST response data
}
}
}
You should normally be able to use async/await inside a catch, just like everywhere else.

Related

Javascript await reading text file

This is probably dead simple, but I can't quite figure it out. I simply want to read the contexts of a text file into a variable. What I have is:
async function load(path) {
try {
const response = await fetch(path);
const text = await response.text();
return text;
} catch (err) {
console.error(err);
}
}
var source_text = load(source_text_path);
console.log(source_text);
To my mind, this should work but only the pending promise is returned and not the text, thought I thought it was awaiting properly.
You need to wait for the load method.
var source_text = await load(source_text_path);
OR
load(source_text_path).then(e => console.log(e))
The function is indeed awaiting as it should, but since it's async, it will always result in a Promise<things> when you return thing.
Which means you should either await it elsewhere:
var source_text = await load(source_text_path);
or then it:
load(source_text_path).then((source_text) => {
console.log(source_text);
})

Async Function Inside Async Function

I am trying to get Data over my API-Endpoint and want to populate my page with the data.
I know that I have to use async/await to be sure that the variable was filled. Therefore I wrote the following lines and want to know that it is possible to write an async function inside an async function. It is working but I am not sure if it is the correct way:
async function getRoom(id) {
const response = await fetch('/api/zimmer/' + id);
if (!response.ok) {
const message = `An error has occured: ${response.status}`;
throw new Error(message);
}
const rooms = await response.json();
console.log(rooms);
return rooms;
}
async function getSelectedItem() {
var e = document.getElementById("Objekt");
if (e.value > 0) {
zimmer_select.disabled = false;
var response = await getRoom(e.value);
console.log(response);
response.forEach(function(element) {
console.log(element);
});
} else {
zimmer_select.disabled = true;
}
console.log(e.value);
}
I think it is fine to use it this way actually.
If you think about, sometimes you have to use async inside async. What if you have some async function which fetches data and you have to loop over that data and await for something. If you loop it with for each you won't be able to use await, so you should put async before it. So as long it's clean and have no other way, I think it is fine to use async inside async.

Call API untill certain response

I really struggle with async functions in Javasctipt. Here I have async function that calls api and saves the result. It is working fine but I need to make a loop now so this api is called untill certain condition is met. I understand that it needs to be done using await but I just can't figure out how exactly.
I tried setting up if statement and then doing something like "if condition is not met" setTimeout(getResults()); (repeat the call to async function).
async getResults() {
try {
const res = await axios(`https://blablabla`);
this.result = res.data.info;
} catch (error) {
alert(error);
}
}
async getResults() {
try {
let i = 100;
while(i-->=0){
const res = await axios(`https://blablabla`);
this.result = res.data.info;
if(this.result == 'some process finished')
{
return this.result;
}
//else retry
}
} catch (error) {
alert(error);
}
just use some cycle like while(true). And repeat body of cycle until your conditions are met

How to control Javascript's async/await behaviour in case of an error?

I was trying ES6 Async/Await feature and it's easier to implement using async/await rather than Genrators and Promise.
For instance when we are calling a promise function(getActiveSession in the below snippet) from async function - if Promise fails it will be caught in the catch block and is handled.
async function createSession(context) {
try {
let activeSession = await getActiveSession(context);
if (activeSession) {
return activeSession;
} else {
let session = await createNewSession(context);
return session;
}
} catch (createSessionException) {
throw createSessionException;
}
}
What if I need to continue without breaking the program flow? i.e I need to create a newSession if getActiveSession fails.
Currently, if getActiveSession promise is rejected with error No Session Found - same error message is thrown to createSession as well.
What if I need to continue without breaking the program flow? i.e I need to create a newSession if getActiveSession fails.
Then create a new session if getActiveSession fails (or returns null):
async function createSession(context) {
try {
let activeSession = await getActiveSession(context);
if (activeSession) {
return activeSession;
}
} catch (ex) { }
return await createNewSession(context);
}
Add the logic you want in your catch block instead of throwing an error.
The error you rethrow in catch block is in fact the reason why your async function reject instead of resolving.
async function foo() {
try {
throw new Error("let's go to the catch block")
} catch (e) {
return safelyCreateSession()
}
}
if you still want to rethrow from the function, this means you'll want to handle this in the function that calls it:
async function main() {
let result;
try {
result = await aFunctionThatThrows()
} catch (e) {
result = aFunctionThatDoesNotThrow()
}
// use result
}

react-native async fetch, undefined error

When calling GetByUsername, the execution jumps to catch block
but err is undefined. The api is working because the equivalent promise style code .then().then().done() works, but I'd like to write in this async / await style better. How can I debug it ?
var cli = {
GetByUsername: async function(username) {
try {
let resposne = await fetch(`http://api.example.com?username=${username}`);
return response;
} catch(err) {
debugger;
}
}
}
edit:
By looking at react-native's package.json it seems that the fetch implementation used is node-fetch and babeljs as transpiler.
try this:
const response = await fetch(`http://api.example.com?username=${username}`);
const jsonData = await response.json();
// then you can use jsonData as you want
I found the problem was a misspelled variable, so I was returning a non existing variable, that cause the execution to end in the catch block with an undefined Error.

Categories

Resources