Transmitting a Commitment as a Response in the HTTP protocol

I'm diving deeper into the world of promises in javascript. I grasp the fundamental syntax where promises are used by clients for handling asynchronous tasks like this:

async function fetchMovies() {
  const response = await fetch('/movies');
  // waits until the request completes...
  console.log(response);
}

From what I gather, fetch returns a promise that resolves as soon as the API --in this case /movies-- responds.

A thought crosses my mind: Is there a scenario where the API endpoint itself returns a promise as a response to an HTTP request? Something along these lines:


...
const app = express();
...
app.get('/',function (req, res) {
    let promise = new Promise((resolve,reject) => {
        ...heavy work here (possibly calling another fetch or something)
        resolve({"msg":something}); 
    })
   
    return res.send(promise);
});

On the client side, not much would change since it still receives a promise and must wait for it to resolve before processing the response. However, sending the promise immediately would free up the API's CPU to handle other tasks concurrently.

My hunch is that this might not be practical as I haven't come across it in practice. It seems like resolving promises within one realm, either an API or client, makes more sense than interchanging them. Still, I wanted to ponder over this concept in case I am overlooking something.


PS: During my attempt at implementing the second code snippet, I encountered various errors. Thus, I contemplated more on the viability of the idea rather than fixing the bugs in the implementation.

Answer №1

From my understanding, fetch returns a promise that is resolved once the API - in this case /movies - responds.

Contrary to that, the function actually immediately returns a promise. A promise serves as a way for the caller to manage a 'future result'. It's essentially a promise of a result that is available right away but gets fulfilled later on.

I'm curious if there are any scenarios where the API endpoint itself sends back a promise as a response to an HTTP request. For instance,

It appears you're discussing HTTP APIs here. Typically, data returned by HTTP APIs comes in JSON (or XML, or Protobuf) format. Promises are not compatible with these formats because they represent more than just data; they involve event handling code.

. However, the API could immediately send the promise and have some unused CPU time for other tasks.

Remember that a promise isn't a magical container holding an operation running independently from the CPU. The promise you return must still be resolved by some executing code. You can't simply transfer this workload to another machine (or browser) by sending an event handler, even if that were feasible.

It's akin to sending a callback to a client. There still needs to be something that triggers that callback, likely performing the heavy lifting. The callback itself doesn't handle all the work.

Answer №2

Utilizing HTTP methods like fetch involves implementing the stream api.

The Fetch API utilizes Request and Response objects source

Response.body - A ReadableStream of the body contents. source

The ReadableStream interface within the Streams API represents a readable stream of byte data. The Fetch API provides a tangible example of a ReadableStream via the body property of a Response object. source

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

How can I convert a string to an integer in Node.js/JavaScript in terms of cardinality?

Imagine a scenario where a user can input any string such as "1st", "2nd", "third", "fourth", "fifth", "9999th", etc. The goal is to assign an integer value to each of these strings: "1st" -> 0 "2nd" -> 1 "third" -> 2 "fourth" -> 3 "fifth" -&g ...

Unable to generate production package

NPM version (npm --v): 5.4.2 Gulp version (gulp -v): [email protected], [email protected] JHipster version: 4.6.1 Node version: 6.11.3 I am facing difficulties in generating a production package for my application. The process of running ...

Should I include one of the dependencies' dependencies in my project, or should I directly install it into the root level of the project?

TL;DR Summary (Using Lodash as an example, my application needs to import JavaScript from an NPM package that relies on Lodash. To prevent bundling duplicate versions of the same function, I'm considering not installing Lodash in my application' ...

Learn the technique of invoking a sub component's method from the parent component in Vue.js

I am looking to trigger a method in a sub component from the parent component in Vue.js in order to refresh certain parts of the sub component. Below is an example showcasing what I aim to achieve. Home.vue <template> <componentp></compo ...

Failed to load the .dll file using ffi-napi while working on a Mac operating system

I've been attempting to load a .dll file in a simple JavaScript file, following the guidance provided in the official documentation here. When I follow the code from the official docs, everything works smoothly: var ffi = require('ffi-napi' ...

Is it possible to define RabbitMQ login credentials in a node.js application?

Recently, I have been utilizing rabbit.js for connecting to RabbitMQ from a node.js application. However, I have encountered an issue: Error: Channel closed by server: 403 (ACCESS-REFUSED) with message "ACCESS_REFUSED -operation not permitted on the de ...

Jenkins encounters difficulties when attempting to install npm packages

Having an issue with my Jenkins setup that seems quite peculiar. ------ 1 ------ In this scenario, I've set up two build steps using shell scripts: First: npm install jspm Second: npm install browser-sync During Checking out Revision e05c2140a014 ...

What is the best choice for a Geolocation App: REST API or Socket.io?

Currently, I am working on a project that involves tracking moving cars. I am contemplating whether to update the location every time it changes and send it over through the socket. Alternatively, would it be more efficient to create a REST API where the ...

Acquire a JPG file from IPFS utilizing the Infura API and ipfs-http-client in a React project

Using the infura API and ipfs-http-client, I successfully uploaded a jpg image onto IPFS. The file was selected through an input with type=file, triggering the onchange event listener. // necessary imports const IpfsHttpClient = require("ipfs-http-cli ...

Attempting to show the name in AngularJS

I've been working on mastering Angular JS, but I'm facing a challenge with displaying the user I just added to the database on the next page. While I can display other users, the newly added user's data just won't show up! I've tri ...

Implementing a data retrieval process in MongoDB for displaying on a localhost server using Node.js

Currently, I'm in the process of developing a to-do list application using mongoDB and node.js. The concept is simple - you enter your tasks and then click 'add'. I've managed to establish a connection with the database successfully. Ho ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

Unable to access API endpoint for retrieving items as described in the Express/React tutorial on Pluralsight

Currently, I am going through a tutorial on React, Express, and FLUX. Unfortunately, I have encountered a roadblock in the form of a CANNOT GET error when trying to access my API data. https://i.stack.imgur.com/RbUzf.png In the server file under Routes > ...

What are the steps for implementing async.applyEachSeries in a Node.js application?

I would greatly value it if someone could provide a detailed example illustrating the utilization of the async.applyEachSeries function. async.applyEach([performTask1, performTask2], 'parameter', callback); // here is an example of partial appl ...

Retrieving data from MongoDB and saving it to your computer's hard drive

I've asked a variety of questions and received only limited answers, but it has brought me this far: Mongoose code : app.get('/Download/:file(*)', function (req, res) { grid.mongo = mongoose.mongo; var gfs = grid(conn.db); var fi ...

Debian on Node Express always serves index.html by default

I am currently facing an issue with my node express server. It works correctly on a Windows system, but when running on Debian, it always returns index.html. Whenever I try to access localhost:port/ in the browser, it displays index.html. The problem is t ...

Angular2 and Express: The Dynamic Duo

I am encountering an issue with my Angular2 app that is using Express. The problem arises when I have a URL like /v2/tickets?filterId=321 and upon page reload, it changes to /v2/tickets/?filterId=321, disrupting the Angular2 routing process. Upon checkin ...

Steps for uploading a file with WebdriverIO

Currently, I am in the process of converting this Ruby code using the selenium-webdriver gem into Node.js with WebdriverIO: @webdriver.navigate.to "https://imgur.com/upload" element = @webdriver.find_element(:id, 'global-files-button') element.s ...

Save the output of a knex query to a variable

I'm struggling to assign the result of a select query using Knexjs to a variable. Here is my code: function getAllCategories() { let categories; categories = database.from("categories").select("category").then(function (rows) { for (let row of ro ...

Storing JSON data from multiple requests in a NodeJS application and saving it to a

I have been developing a web crawler that is capable of retrieving and parsing data, then storing it in my MySQL database. While I have succeeded in storing the results, I am facing an issue when attempting to end the connection. The technologies I am usi ...