简体   繁体   中英

Send Response in 'then' after Promise resolves

I want to display the json i got from the search for localhost:8400/api/v1/search . But I have no idea how.

I'm using the Elasticsearch Javascript Client

my routing:

'use-strict';
const express = require('express');
const elasticsearch = require('../models/elasticsearch.js');

const router = express.Router();

router.get('/api/v1/search', elasticsearch.search);

for accessing the ElasticSearch DB

const es = require('elasticsearch');

let esClient = new es.Client({
  host: 'localhost:9200',
  log: 'info',
  apiVersion: '5.3',
  requestTimeout: 30000
})

let indexName = "randomindex";

const elasticsearch = {

  search() {
    return esClient.search({
      index: indexName,
      q: "test"
    })
      .then(() => {
        console.log(JSON.stringify(body));
        // here I want to return a Response with the Content of the body
      })
      .catch((error) => { console.trace(error.message); });
  }
}

module.exports = elasticsearch;

Since you add elasticsearch.search as the route handler, it will be invoked with some arguments.

Change the signature of the search method to search(req, res) .
Then just call res.send(JSON.stringify(body));

See https://expressjs.com/en/4x/api.html#res for more details

Firstly, the route handlers for express routes always have (request, response, next) as it's parameters. You can use the response object to send data back to the client.

Instead of passing the elasticsearch.search method as a route handler, you can write your own route handler and call elasticsearch.search in there, so you still have access to the response object. For example:

function handleSearch(req, res, next) {
  elasticsearch.search()
    .then(function(data) {
      res.json(data)
    })
    .catch(next)
}

And structure your search function like so:

const elasticsearch = {

  search() {
    return esClient.search({
      index: indexName,
      q: "test"
    })
    .then((body) => body) // just return the body from this method
  }
}

This way you separate your concerns of querying elastic and handling the request. You also have access to the request object in case you want to pass any query string parameters from your request to your search function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM