Is there a way for me to either fulfill a promise or face failure?

Currently, I am working on creating a Thennable function that may return a promise based on its parameters. However, there is a possibility that the parameters are invalid which would require breaking the promise chain with something unexpected. What can be used in this scenario? Here is a rough outline of my current function:

function getThumbnailFromClips(res, clips) {
  var clips = content.clips;
  if (clips.length == 0) {
    res.status(400).send(new Error("Empty playlist"))
    // >> WHAT SHOULD BE RETURNED HERE?  <<
  } else {
    var pick1 = Math.floor(Math.random() * clips.length);
    var sql1 = ` SELECT  <details omitted>   `;
    let promise = client.query(sql1)
    return promise
  }
}

This function is typically called from an app.post callback like so:

app.post("/foo", (req,res)=>{
  getClips(req)
  .then((clips)=>getThumbnailFromClips(res,clips))
  .then(((result)=>createDatabaseEntry(result)))
  .catch(/*etc*/)
})

Also, should it be considered better practice to handle sending the 400 result code within the outermost caller instead?

Answer №1

The concept of alternating between sending a response and returning something entirely different is not advisable in terms of design. Consistency in return values is key; if you are occasionally returning a promise, then it is best practice to always return a promise. Errors can easily be relayed back through a rejected promise.

Likewise, it is important to avoid having request handler code paths that inconsistently send responses from different locations. This approach makes it difficult to maintain the code effectively ensuring that only one response is sent at all times and that errors are handled uniformly. It is recommended to centralize the response handling within the main request handler code rather than dispersing it throughout sub-functions. Sub-functions should focus on executing operations and returning results, while the request handler body orchestrates these functions, processes their results, and sends the response.

A suggested implementation could look like this:

function getThumbnailFromClips(clips) {
    const clips = content.clips;
    if (clips.length == 0) {
        const err = new Error("Empty playlist");
        err.status = 400;
        return Promise.reject(err);
    } else {
        const pick1 = Math.floor(Math.random() * clips.length);
        const sql1 = ` SELECT  <details omitted>   `;
        return client.query(sql1);
    }
}

app.post("/foo", (req, res) => {
    getClips(req)
        .then(getThumbnailFromClips)
        .then(createDatabaseEntry)
        .then(() => {
            // insert appropriate success status here
            res.send({status: "ok"});
        }).catch(err => {
            // handle all errors here
            const status = err.status || 500;
            res.status(status).send(err);
        });
});

Additionally, note that var is considered outdated. It is recommended to use const or let instead.

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

What is the best way to verify a date in the format (yyyy-mm-dd) using jQuery?

I'm in the process of validating a date with the format (yyyy-mm-dd). I came across a solution, but it's not quite what I need as it's in the format (mm/dd/yyyy). You can check out the solution here: http://jsfiddle.net/ravi1989/EywSP/848/ ...

Creating a seamless integration between a multi-step form in React and React Router

I've been learning how to use React + ReactRouter in order to create a multi-step form. After getting the example working from this link: , I encountered an issue. The problem with the example is that it doesn't utilize ReactRouter, causing the ...

HTML: Efficiently updating multiple cell contents in a large table using jQuery or JavaScript

Hello, I am currently working on developing an HTML page that consists of a large data table. My goal is to have the data in the table update dynamically as the user interacts with various controls on the page, without having to reload the entire page. ...

Use Javascript to set cookies and remember the show state when clicked

Can you offer some advice? I am looking to add cookies to my simple JavaScript code. Currently, the div is displayed when clicking on a link, but it hides again when the page reloads. I would like to implement cookies to remember the show state for 7 days. ...

My JSON request seems to be malfunctioning and I can't figure out why

I've generated a URL that I need to forward to the police data API. var api_url="http://policeapi2.rkh.co.uk/api/locate-neighbourhood?q="+latlon; document.write(api_url); The URL functions correctly when manually entered into a browser, but I requir ...

What is the method to convert Javascript values from pixels to percentages?

Is it possible to change the scrolltop value dynamically based on a percentage of the user's screen size? I've been trying to achieve this using JS but haven't had any luck. Here is a link to a codepen that showcases the issue: [link] (http ...

Partial View fails to render on the webpage

After submitting information from my first partial view, I attempted to load a second partial view. However, upon submission, the first partial view just refreshes and remains on the same page instead of loading the new view. Despite setting up my controll ...

Tips on utilizing CSS modules in React without changing class names

After starting to use css modules in my react project, I quickly realized the struggle of changing classnames to fit the requirements of css modules. For example, if we have a component using regular css: import React from 'react' import ". ...

Fetching an image from a fixed storage location with the help of Express JS in Angular 2

Utilizing node js and express on the backend, I have a static folder filled with various images. My current task involves loading these images using angular 2 on the client side. Below is a snippet of my code: Backend side: app.use(express.static(__dirna ...

Accessing Private Files with Signed URLs from AWS S3

Issue: The challenge is to securely allow users to upload a file and retrieve it later. The files are stored in private Buckets and objects using S3 pre-signed URLs for uploading. However, fetching the file poses a problem as the signed URLs expire after ...

Extract the content from the division and set it as the image source

Looking for a way to retrieve the content from a div and insert that into the 'src' parameter of an image. Working on a project where JSON is used to load translation files, preventing me from loading images directly, but I want to at least load ...

Creating an error handler in PHP for dynamically adding or removing input fields is a crucial step in ensuring smooth and

I designed a form with multiple fields, including a basic input text field and dynamic add/remove input fields. I successfully set the first field as required using PHP arguments, but I'm struggling to do the same for the additional fields. I need as ...

Encountering the 401 (Unauthorized) error while attempting to delete data in loopback?

I have a model called companyUsers and when I send a GET request, I am able to retrieve all the data successfully. However, when I try to make a DELETE or PUT request, I encounter a 401 (Unauthorized) error. For example, I made a DELETE request using the ...

The Tab component's onClick event is nonfunctional

I am currently utilizing the Tab feature from the material-ui library in my React project. As I try to come up with a workaround for an issue I am facing, I notice that my onClick event listener is not being triggered. An example of one of the tabs: < ...

Preserving input data based on click and change events

Upon form submission, I encounter an issue with displaying only the divs that contain fields with saved values. The form saves user-entered values using PHP, where some of the fields are initially hidden within div elements until an onclick or onchange eve ...

I'm encountering an error in my terminal while running the code

ERROR *Server started on port 4000 Database ErrorMongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 (node:1616) UnhandledPromiseRejectionWarning: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017 at NativeConnection.Connec ...

Looking for an easy solution in RegExp - how to locate the keys?

Similar Inquiries: Retrieving query string values using JavaScript Utilizing URL parameters in Javascript I am tasked with extracting specific keys from a series of URLs where the key is denoted by 'KEY=123'. My goal is to identify and e ...

What is the process for updating an item in Sequelize?

Seeking help with updating an object in Sequelize. Here is the code I'm using: const updateEmployee = async (req, res) =>{ let {full_name, email, phone_number, address} = req.body const id = req.params.id; Employee.findOne({ wh ...

Transferring data from JavaScript to PHP using the $.ajax method for storing information in a MySQL database

I am attempting to make a POST call from a JavaScript file to a PHP file in order to insert a variable into a MySQL database. Here are the basic files I am working with: 1° PHP file for sending the call <html> <head> <script ...

What's the best way to handle variables and numerical calculations within PHP loops when dealing with forms?

I'm currently developing a basic PHP page where users can choose how many numbers they want to add together. After selecting the quantity, they input the numbers on a new page, click a button, and then see the sum displayed. The challenge I'm fa ...