Encountered an abrupt termination of JSON input while implementing Promise.all() alongside the fetch method's put operation

Encountered an issue with JavaScript while attempting to retrieve mail content from an API and update its read status simultaneously. The error message displayed in the console is:

SyntaxError: Unexpected end of JSON input
    at inbox.js:98

The error promise logged is shown below.

1: Promise
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: SyntaxError: Unexpected end of JSON input at http://127.0.0.1:8000/static/mail/inbox.js:98:30
message: "Unexpected end of JSON input"
stack: "SyntaxError: Unexpected end of JSON input\n    at http://127.0.0.1:8000/static/mail/inbox.js:98:30"

The code at line #98 is:

let res2 = response[1].json();

The complete JavaScript code is as follows. Upon inspection, it seems that the issue stems from 'res2' since its return value is 'rejected'. Various attempts were made to resolve this without success. Additionally, it is unclear why this error is not caught by the 'catch' function. Thank you for any assistance provided.

Despite receiving a 'SyntaxError', both 'fetch' functions have executed successfully...

async function show_single_mail(email_id){
 
  // Code to display email content

  document.querySelector('#mails_table').style.display = 'none';

  const email_div = document.createElement('div');
  document.querySelector('#emails-view').append(email_div);

  // Retrieve email content and update read status concurrently

  const option2 = {
    method: 'PUT', 
    body: JSON.stringify({read: true})}

  Promise.all([fetch(`/emails/${email_id}`), fetch(`/emails/${email_id}`, option2)])
    .then(response => {
      let res1 = response[0].json();
      let res2 = response[1].json();
      console.log([res1, res2]);
      return Promise.all([res1, res2])
    })
    .then(results => {
      result = results[0];
      email_div.innerHTML = 
      `<h3>Subject: ${result.subject}</h3><br>` +
      `<p>Sender: ${result.sender}</p><br>`+
      `<p>Receiver: ${result.recipients}</p><br>`+
      `<p>Time: ${result.timestamp}</p><br>`+
      `<p>Content: ${result.body}</p>`;
    })
    .catch(err => console.log(err))
}

Answer №1

When making parallel requests using

Promise.all([fetch(...), fetch(...)])
, it is important to check if the requests were successful and returned JSON data. The fetch method does not reject on 4xx status codes, so you need to handle this scenario properly.

If your server only returns text for unsuccessful requests or the response does not have a valid JSON body, parsing errors may occur. Therefore, before trying to read the body of the responses, ensure that they are successful and contain valid JSON data.

One approach is to filter the responses based on their status code (2xx for successful, others for unsuccessful) and then process them accordingly. You can choose to parse JSON for successful responses and display them, while handling failed requests separately.

Another option is to differentiate between responses that contain JSON data and those that do not by checking the content type from the headers. This allows you to appropriately parse the data based on its format.

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

Exploring JSON data in a systematic manner

Currently, I am working with a JSON string and encountering a problem. When I run console.log(record.seenTime.time.seenEpoch), I am able to see the correct information. However, if I try console.log(record.seenTime.time[0].seenEpoch), I receive an error m ...

Utilizing JSON in Asp.net MVC

I need help with calculating the addition of two numbers in ASP.NET MVC. Below is my code snippet. public ActionResult Index() { return View(); } public JsonResult Calculate(int a,int b) { return Json(a + b); } The c ...

Eliminating the use of am/pm and implementing a 24-hour format on the x-axis of a time series

Currently, I am attempting to create a time series plot with second precision in the format of HH:mm:ss (24 hours per day), as indicated in the documentation provided by moment js. However, I have encountered an issue where the format I specify is not bei ...

When the jQuery Div is moved to the right, it gradually shrinks in size, yet remains unchanged when

I have been making updates to this page, which you can view here. When you select "Let's Get Started" and then proceed with the right arrows, the divs smoothly move to the left without shrinking. However, when clicking on the back or left arrows, the ...

How do I hide a dropdown menu when the selector's value changes in iOS6?

I'm currently developing a hybrid application using Worklight. When I tap on a select control, a native dropdown appears. However, when I choose an option and the onchange event is triggered, the dropdown doesn't disappear unless I tap on the do ...

The People and Groups selection dialog is displaying incorrectly in IE 10

I've been working on a Sharepoint web application and have created a site column of type “People or Group”. This should be automatically associated with a user selection dialog as shown below: However, as you can see in the image above, the users ...

Authorization in Confluence REST API

Currently, a user is logged in to Confluence; There is an external web application that saves attachments to a specific page. In order to make REST calls from the external app, I need the user's credentials for Confluence (which I do not have because ...

Using @ResponseBody in Spring to return a specific variable name in json format

I recently encountered a challenge with my Spring controller method that is sending a collection of objects in JSON format to the client: @RequestMapping(value="/admin/rawreads/unknowntags", method=RequestMethod.GET) public @ResponseBody Collection<Raw ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Leveraging react props with the .map method

Imagine having this render function in one of your components. You've passed a changeTid prop function from the parent element. Parent Component: <RequestsList data={this.state.data} changeTid={this.changeTid} /> Child Component: (Using ES6 ...

JavaScript encountered a runtime error due to a script error: The object does not have support for the property or method 'row' when using the datatables plugin

Currently, I am utilizing the datatables plugin for my application which can be found at the following link: https://datatables.net/examples/api/row_details.html After clicking on a row in the table, I encountered the error message below. I am having dif ...

Exploring the integration of React Suspense boundary to handle data fetching from API following specific triggers

Hello, I am relatively new to React and JS. I am currently working on implementing the React Suspense boundary for a component that requires fetching data from my backend API. I followed an example that provided functions like fetchData and wrapPromise [h ...

Definition of JSON Schema attribute: Field schema not supported for field... : Type of field is undefined

I am in the process of creating a form that is based on a JSON schema and utilizing the react-jsonschema-form component for ReactJS. The purpose of this form is to allow users to input various settings (such as CSS/HTML selectors) that will be used to ext ...

Refreshing the browser does not load the Angular2 component and instead shows a 404 error

During my exploration of Angular 2, I developed a basic restaurant management application. Now, I am delving into more advanced techniques such as creating an app bundle, minification, and optimizing the application. The authentication component in my app ...

Unable to extract attributes from a different model within Sails.js

I'm working on populating a customer model with attributes from the address.js model. However, when trying to post JSON using Postman, I keep getting a 500 Validation Error and struggling to pinpoint the cause of the issue. Any assistance would be gre ...

Differences in how line breaks are handled in script output have been observed when comparing Atom and Notepad

Currently, I am utilizing a small script that generates a .txt file and inputs some data into it. Strangely, when I open the .txt file in Atom, the content appears on separate lines as I intended. However, when I access the same file in notepad, all the co ...

What is the best way to add content to fill the empty space left after a column has been hidden in a column

Is there a way to automatically adjust the space when a column is hidden by clicking on the legend item? <div id="container" style="height: 300px"></div> <script src="http://code.highcharts.com/highcharts.src.js"></script> var ...

Tips for preventing multiple clicks when posting AJAX requests in jQuery

Using Django, I was able to create a website and implement a voting page with jQuery AJAX. The code works perfectly fine as shown below: <!doctype html> <html> <head> <script src="jquery-1.10.2.min.js"></script> <met ...

Error encountered at / - undefined local variable or method `parameters' for main:Object (Executing Stripe Charge with Stripe.js)

Encountering an error with the code below while attempting to create a Stripe charge using Stripe.js. Below is my web.rb file: require 'json' require 'sinatra' require 'sinatra/reloader' require 'stripe' get &a ...

Using React front end in combination with Spring method

Hello there! I am currently working on a small project that involves using React for the front end and Spring Java for the backend. In my Spring Controller class, I have a method like this: @CrossOrigin(origins = "http://localhost:3000/") @Ge ...