Using the point-free approach to express and calling response.json does not function properly within Promise.then

Today, I was quite surprised by something that I came across. Within a bunch of express route handlers, I found some code snippets that looked like this (there are more function calls but for the sake of clarity, I've simplified it):

app.get('/api/foo', (req, resp) => {
  Promise.resolve({one: 1})
    .then(data=>resp.json(data))
})

As someone who considers themselves a proficient javascript programmer, I thought I could simplify the code by removing the anonymous function and calling resp.json directly inside the then function:

app.get('/api/foo', (req, resp) => {
  Promise.resolve({one: 1})
    .then(resp.json)
})

However, when I attempted to do so, I encountered an issue where I never received a response and instead saw this error in the node console:

Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'app' of undefined

On the surface, it seems like .then(resp.json) and .then(data=>resp.json(data)) should be interchangeable. It appears to be a scope-related problem, but I would appreciate an explanation and possibly a workaround.

Answer №1

One reason for this behavior is that the resp variable represents an object with its own set of properties. Therefore, it is likely that the data needed by the json function is stored within this resp object.

When you pass only resp.json to the then function, you are essentially providing just the json function on its own without any reference to the original resp object or its data. In other words, the then call is merely borrowing the json function from the resp object without retaining its context or values.

It is probable that the json function body makes use of this at some point, which could result in receiving an incorrect (potentially global) object instead of the expected resp.

To resolve this issue, you can try:

   Promise.resolve({one: 1})
    .then(resp.json.bind(resp))

Answer №2

The reason they are different is due to the behavior of the this keyword in javascript.

In essence, when you use resp.json(data), the function is called with this===resp, whereas with resp.json, the function is called with this===global.

To resolve this issue, you can pass the function with bound parameters using .then(resp.json.bind(resp)) (or utilize an arrow function).

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

The slice() function is displaying the correct output in the console, but the string is not being updated in the <td>

I am facing an issue where the console displays the expected substring, but the original string in the HTML remains unchanged. The goal is to truncate any long text within each table <td>. It's important to note that I'm specifically avoi ...

I am unable to comprehend the function definition

I have familiarity with different types of JavaScript function declarations such as expression functions and anonymous functions. However, I am unsure about the syntax used in these two specific functions: "manipulateData: function (input)" and "getDataByI ...

Strategies for digitally boosting review numbers

I am currently developing an application with the following tasks at hand: Creating two models - Product and reviews on Product. I have successfully created a Schema for Product and implemented all APIs (add product, read product, read product by id, updat ...

Arrange items in an array by two criteria

Sorting elements in a JavaScript array can be tricky, especially when trying to order them based on specific criteria like Ptr and Outputs values. In this case, the desired ordering is Node 0 -> Node 2 -> Node 1, where the Output of an element matche ...

Exploring AngularJS: Retrieving a list of filenames from a specified directory

In the public directory of my application, there is a folder named 'x'. I have the path name to the folder (/path/to/dir/x) but I am unsure of the names of the files within it. How can I retrieve the file names and provide URL links to them in an ...

Experiencing difficulties with AngularJs as onblur event is not functioning properly when the input field is empty

I am currently working on a form that allows users to input data. I am facing an issue where if a user enters a number, deletes it, and moves away from the input field, it will display an error message. However, I want the error message to display only i ...

Tips for keeping track of data for various individuals

I am in the process of developing a Dungeons and Dragons discord bot for my friends. I would like to enable the players to use a specific command to input their character information such as first/last name, race, class, and more. I attempted to utilize m ...

tips for transforming a javascript string into a function invocation

I am faced with the challenge of turning the string logo.cr.Button into a function call. Here is the code I'm working with: logo.cr.Button = function(){ //something } var strg = 'logo.cr.Button'; strg(); When I attempt to execute strg(); ...

Trouble accessing the Ionic SQLite database: Unable to open

I encountered some errors while attempting to connect my ionic app to a database. I am currently running the app on an android device using Google Chrome DevTools to troubleshoot the issue. Check out the createDatabase() function and the specific error th ...

Learning the art of Javascript programming within the HTML5 realm

Seeking assistance with a JavaScript project - I'm attempting to develop a Bubble Buster game reminiscent of pong, but with multiple bubbles. The goal is to have falling bubbles on screen (roughly 100 in total) in various colors dropping from random l ...

What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this? **Stackblitz link:** : https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fa ...

Is it necessary to compile Jade templates only once?

I'm new to exploring jade in conjunction with express.js and I'm on a quest to fully understand jade. Here's my query: Express mentions caching jade in production - but how exactly does this process unfold? Given that the output is continge ...

What is the best way to save the outcomes of several asynchronous $.get calls into an array?

I have a challenge where I need to retrieve data from an API for each item in an array, and then store that data in another array for further processing. However, I suspect the issue lies in the asynchronous nature of the requests, as the data may not be ...

Hey there, I'm having trouble with button B. It's not working, do

Why doesn't my Button B display an alert popup? Here are the code snippets from separate files: .html: <html> <body> <input type="button" class="popup" value="BUTTON A"/><br> <input type="button" class="displaymeh ...

Assigning nested JSON values using Jquery

My JSON data structure is as follows: { "Market": 0, "Marketer": null, "Notes": null, "SalesChannel": null, "ServiceLocations": [ { "ExtensionData": null, "AdminFee": 0, "CommodityType": 0, ...

A guide to retrieving data in React with useSWR whenever the state changes

In a specific scenario, I need to be able to choose users from a dropdown menu. Once a user is selected, the app should display that user's data. Upon loading the page, the app fetches the data for the first user in the array allUsers?.[0]: const [us ...

"Having trouble with sound in react-native-sound while playing audio on an Android AVD? Discover the solution to fix this

react-native-sound I attempted to manually configure react-native-sound but I am unable to hear any sound. The file was loaded successfully. The audio is playing, but the volume is not audible on Android AVD with react-native-sound. ...

Possible issue with accurate indexing causing caption error with API images in React

Continuing from: Implementing a lightbox feature in react-multi-carousel for my ReactJS app My application utilizes react-images for the lightbox functionality and react-carousel-images for the carousel. The API provides a title and image data. The issue ...

Dealing with NULL values in a Postgresql database

In the web-survey I created, users are able to select their answers by using radio buttons. To determine which buttons have been selected, I utilize javascript. I have not pre-set any default states for the buttons, allowing users to potentially leave ques ...

Why won't both routes for Sequelize model querying work simultaneously?

Currently, I am experimenting with different routes in Express while utilizing Sequelize to create my models. I have established two models that function independently of one another. However, I am aiming to have them both operational simultaneously. A sea ...