What is causing my function to continue running despite using 'return'?

My goal was to check the success of my request by adding an If condition. If the condition turns out to be true (indicating a bad request), I needed to stop the function and prevent the execution of subsequent commands. Here is an overview of my code:

async function updateUserInfo(userData) {
    const modal = document.querySelector('.userInfos > dialog')
    //modal.close()
    const userToken = getUserToken()

    const nuUserSettings = await fetch(`http://localhost:6278/users`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${userToken}`,
        },
        body: JSON.stringify(userData)

    })
    
    .then(res => {
        if (res.status === 400) {
            return
        }

    })

    console.log('return didn't work function is still running')

    .then(res => res.json()) 
}

I attempted to move the remaining code into an 'else' condition, but it did not work as expected because the operation of '.then(res => res.json())' was not functioning properly.

Answer №1

The issue arises because you are using a return statement inside a then block, which does not halt the main thread.

To resolve this, consider the following approach:

   const response = await fetch(`http://localhost:6278/users`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${userToken}`,
        },
        body: JSON.stringify(userData)
    });
   if (response.status === 400) return;
   return response.json();

It's unclear why there is a second then -> .then(res => res.json()).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

html Implementing a phone number input mask

I am trying to implement a phone number mask for my input field. However, the current method I found removes the visibility of the number "9". How can I ensure that the number "9" remains visible in the following format: +994(__)___-__-__ $(window).load ...

Advanced Text Formatting Tool with Table, Picture, and Document Upload Capabilities

Searching for an open source Rich Text Editor that can handle tables, images, and file uploads while keeping a slim design. Popular options like tinymce or ckeditor are too bulky and lack image and file upload capabilities. ...

The websocket connection to the production host has encountered issues, while it operates smoothly on localhost within Django

I successfully integrated a websocket connection for real-time updates in my Django application. The issue arises when I try to host the application on a public server, as it fails to connect. I am using Daphne server for hosting. Below is a snippet of my ...

Guide to obscuring all instances of a particular subsequence within a <p> tag

I am currently developing a project in Angular that showcases short texts. Within these texts, I aim to blur out specific substrings every time they appear. For example: Tomorrow I will have to go to London. Tomorrow is the day it will happen. My only hop ...

Passing only certain arguments to a function while omitting others without explicitly declaring null values

Using Vue 3 and composable files for sharing functions across my entire app has been a great help. One of my composable files, usePluck.js, is structured like this: import { api } from 'boot/axios' export default function usePlucks() { const p ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...

Is there a way to conceal the contents of a page until all the images have finished loading?

I'm currently working on improving the performance of a website that is loading very slowly. I have already reorganized, compressed and minified the JavaScript and CSS files, but the main issue seems to be with the images. The site contains large imag ...

Verify the compatibility of the device with ScreenOrientation.lock() function - An error occurred indicating that screen.orientation.lock() is not supported on this particular device

I've been trying to implement ScreenOrientation.lock() according to the documentation, but I'm having trouble getting it to work correctly. https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/lock When I use window.screen.orienta ...

I am trying to set a background image specifically for one page in my application, but I am struggling to make it work. As a newcomer, I am still learning how to

I've been working on the code for a login page, but I'm having trouble setting a background image for the page. I know how to set it for the whole application by modifying the app component, but when I try to do the same for this specific compone ...

Is it possible to retrieve the width value when using layout=fill in next/image?

<Image alt="image_example" src="/image_example.png" layout="fill" objectFit="none" /> <Test width={?} height={?}/> I developed a straightforward component using next/image. I am interest ...

The component inside the private route is failing to render without a manual page refresh

I am facing an issue with allowing access to users based on their assigned roles. The list of allowed URLs is retrieved in the 'urls' variable within a PrivateRoute component. However, this list does not load immediately after login. It only work ...

What methods do HTML document Rich Text Editors use to incorporate rich text formatting features?

I am curious about the way text in the textarea is styled in rich-text editors. I have attempted to style text in the form but it doesn't seem to change. How does JS recognize the characters typed by the user? Can you explain this process? Edit: Aft ...

Equivalent of window.onkeypress in Typescript and NodeJS

Can someone help me figure out how to accomplish the following: document.addEventListener('keypress', (event) => { // Need this function to trigger whenever a key is pressed }); in a node.js environment using TypeScript or JavaScript? ...

A Vue button that toggles between three states depending on the value in an array

In my Vue project, I am working on loading an array when the page loads. I need to check the status of each line item in the array and display a specific button for each status using a 3-way toggle. Although I believe I understand the main concept, I am s ...

How to Integrate AngularJS into an HTML Document?

I have a specific goal in mind: to create a single HTML file without separate JavaScript files. While I know that it's possible to include JavaScript inline within HTML, I'm unsure if the same applies to AngularJS. I've attempted to integrat ...

Performing AJAX requests to web services using Razor view engine

This is the web service call I am using: <wsdl:operation name="upload"> <soap:operation soapAction="http://uri.org/IDA_Command/upload" style="document"/> <wsdl:input> <soap:body use="literal"/> </wsdl:input> <wsdl:output ...

javascript - use Outlook to send an email

Is it possible to send a PDF file using JavaScript? I have a link that, when clicked, should open Outlook with the title and the PDF file as an attachment, along with some body text. Can this be achieved through JavaScript? Thank you. ...

What could be causing my token to not save after registering a user?

I am currently facing an issue when submitting a registration form. While the user is successfully created, the token is not stored in localStorage, which prevents me from being redirected immediately to the app and forces me to log in again. Here is my R ...

Directive customization through comprehension expressions

Python is where I spend a lot of my time, so I'm really drawn to the comprehension_expression syntax within Angular's ngOptions. However, I would love to see this syntax extend to other inputs, such as with an ng-list. For instance, let's s ...

Glowing Rhandsontable - Custom Renderer - Apply color based on factor (Palette)

I have successfully generated a dataset where I assigned color codes to a column based on values from another column. colourCount = length(unique(Desc.File$VARIABLECODE)) getPalette = colorRampPalette(brewer.pal(9, "Set1")) Colors <- getPalette(colour ...