Dispatching server reply upon successful promise fulfillment

I am currently running a simple express server that includes a loop to check every domain in an array. The results of this process are being stored in an array called results within each .then statement of the promise. My question is, how can I send the results in the server response after completing this promise block? Should I use a callback and call res.send(results) once the promise is completed? Alternatively, is it possible to achieve this from within the promise using .finally? Or should I utilize the express next parameter instead? I am uncertain about the best approach.

const whois = require('whois-info');
const express = require('express');
const app = express();

app.get('/domainfinder/domain/:domainURL', (req, res) => {
  //const domainURLs = req.params.domainURLs;

  let tests = ['google.com', 'nomatchdomain.com', 'notfounddomain.me'];

  let results = [];

  [...tests].forEach(domain => {
    whois.lookup(domain)
      .then(data => results.push(data))
      .catch(e => console.log(domain, e.message))
  });

  res.send(results);
});

app.listen(3000, () => console.log('App listening on port 3000!'));

Answer №1

To handle errors, make sure to invoke next(err), and in the then callback, use res.send(results):

const whois = require('whois-info');
const express = require('express');
const app = express();

app.get('/domainfinder/domain/:domainURL', (req, res) => {
  //const domainURLs = req.params.domainURLs;

  let tests = ['google.com', 'nomatchdomain.com', 'notfounddomain.me'];

  Promise.all(tests.map(domain => whois.lookup(domain)))
      .then(results => res.send(results))
      .catch(e => next(e))
  });
});

app.listen(3000, () => console.log('App listening on port 3000!'));

Answer №2

There are three different options:

Option 1: Use async/await (executes lookups one by one):

const whois = require('whois-info');
const express = require('express');
const app = express();

app.get('/domainfinder/domain/:domainURL', async (req, res) => {
  //const domainURLs = req.params.domainURLs;

  let tests = ['google.com', 'nomatchdomain.com', 'notfounddomain.me'];

  try {
    let results = [];

    for (const domain of tests) {
      results.push(await whois.lookup(domain));
    }

    res.send(results);
  } catch (e) {
    // handle error
  }
});

app.listen(3000, () => console.log('App listening on port 3000!'));

Option 2: Use Promise.all (executes all lookups at once):

const whois = require('whois-info');
const express = require('express');
const app = express();

app.get('/domainfinder/domain/:domainURL', (req, res) => {
  //const domainURLs = req.params.domainURLs;

  let tests = ['google.com', 'nomatchdomain.com', 'notfounddomain.me'];

  Promise
    .all(tests.map(domain => whois.lookup(domain)))
    .then(results => res.send(results)
    .catch(e => { /* handle error */ });
});

app.listen(3000, () => console.log('App listening on port 3000!'));

Option 3: Use reduce (executes lookups one by one):

const whois = require('whois-info');
const express = require('express');
const app = express();

app.get('/domainfinder/domain/:domainURL', (req, res) => {
  //const domainURLs = req.params.domainURLs;

  let tests = ['google.com', 'nomatchdomain.com', 'notfounddomain.me'];

  tests.reduce(
    (p, domain) =>
      p.then(results => whois.lookup(domain).then(data => [...results, data])),
    Promise.resolve([])
  )
  .then(results => res.send(results))
  .catch(e => { /* handle error */ });
});

app.listen(3000, () => console.log('App listening on port 3000!'));

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

Update the heading from h2 to h1 tag

Is there a way to modify the product names on all product pages, switching them from h2 to h1? I am seeking a solution to change the product names to h1 using custom code. <h2 itemprop="name" class="product_title likeh2">Aspen Ágykeret Bársony S ...

What is the process for connecting an event to the <body> element in backbone.js?

Could it be done? For example, like this: ... interactions { 'click button' : 'performAction' } ... ...

The method $.when().done() is failing to execute as expected

I am encountering an issue with the $.when().done() functions in jQuery. Can someone please provide assistance? Even when I use $.when().done() with a combination of ajax calls and non-ajax call methods, the non-ajax call is executing before the ajax calls ...

Creating dynamic routes in Angular Router without using a forward slash: a step-by-step guide

I have a routes array set up where I want any route containing "the-" to point to the first component, and all other routes to point to the second component. [ { path: 'the-:param', component: MyComponent }, { ...

What is the best way to combine cells within a single column?

Exploring the code snippet utilizing ag-grid with Vue 3. <script setup lang="ts"> import "ag-grid-community/dist/styles/ag-grid.css"; import "ag-grid-community/dist/styles/ag-theme-alpine.css"; import { AgGridVue } from ...

Executing tests using supertest and mocha in Node.js allows for automatic passing of tests on the GitLab CI/CD pipeline

I've been working on running tests using mocha and supertest for an express nodejs app. The problem I've encountered is that the GitLab runner automatically passes the tests even when they are incorrect and should be failing. When I run the test ...

Transfer the image file to a Node.js server using Mongoose and ensure it retains its original filename

Currently, when I upload an image file using nodeJS and express, the image is saved with a random file name and no specific file type. I would like to save the file name with an extension so that it can be displayed properly. In the database, the file na ...

Extracting JSON coordinates using JavaScript

My objective is to locate the closest coordinate and arrange the cities that are nearest. In the console log, I want the output to appear like this: 8 city, 63.50590523722971; 5 city, 76.32168761236873. The coordinates seem correct, but I am struggling wit ...

Mongoose Schema Array/Object: Using the .post method

I am struggling with the following code: // Morosos.js var mongoose = require('mongoose'); const MorososSchema = new mongoose.Schema({ idlor: String, comunidad: String, vivienda: String, demandado: String, importe: String, d ...

Exploring the Depths of GraphQL Mutations: Nesting for

Currently seeking examples of writing nested mutations. Specifically, I am creating a mutation for a recipe object with the following schema: const RecipeType = new GraphQLObjectType({ name: "Recipe", fields: () => ({ id: { type: GraphQLID }, ...

Unable to retrieve the following element in a JavaScript array

I am a beginner in JavaScript and I am attempting to access the next element of an array using an onclick function but so far I have not been successful. var i, len; function quiz() { var quiz_questions = [ "who is the founder of Fa ...

Establishing the properties of an object as it is being structured within a nested data format

I am in the process of creating a unique JSON representation, focusing on object composition to directly set key values during composition. However, I've encountered difficulty composing multiple objects in a nested manner. My goal is to find an expr ...

Passport JS allows you to create a secure login form that redirects users to different URIs based on their role

Currently, I am utilizing Passport JS for authentication management and Express JS to handle routing within my application. At the moment, I have a login route that directs to the /teacher URI upon successful authentication (as depicted below). app.post( ...

What are the implications of using a non-200 status code in my controllers to intentionally trigger an ajax error?

Below is an example of code I have for a remote form: def something @user = User.find_by_email(params[:email]) @success = true @error = nil if !@user @success = false @error = "No such user" elsif <a href="/cdn-cgi/l/email-protection" ...

Adding an image to a select option in HTML using PHP - A step-by-step guide

How can I include an image within a select option using PHP in HTML? The image needs to be retrieved from a database first. echo '<option value='.$ifet['productimage'].'><img src='.$ifet['productimage'].&a ...

"Why is it that the keypress event doesn't function properly when using the on() method

My goal is to capture the enter event for an input field $("input[name='search']").on("keypress", function(e){ if (e.which == '13') { alert('code'); } }); This is the HTML code snippet: <input name="searc ...

What could be the reason for the appearance of this error message: 'Illegal arguments: undefined, string'?

Currently, I am in the process of developing a node.js application where I have created a backend API specifically for user registration. However, when testing it using Postman, I encountered an error message stating 'Illegal arguments: undefined, str ...

What is the method for starting the JavaScript debugger in Google Chrome?

I'm looking to debug some JavaScript code in Google Chrome. Can anyone guide me on how to do that effectively? ...

When making a POST request with $.ajax, object properties can disappear

When uploading a large JSON data set using $.ajax, some properties are getting lost during the upload process. To test this issue, the server returns the first row where a property is missing. Javascript function parseResults(data) { var send = []; ...

How can I create an image that spans the entire width of the screen, Swiper?

var swiper = new Swiper('.swiper-container', { pagination: { el: '.swiper-pagination', }, }); html, body { position: relative; height: 100%; } body { background: #eee; font-fami ...