简体   繁体   English

Promise解决后,在“然后”中发送响应

[英]Send Response in 'then' after Promise resolves

I want to display the json i got from the search for localhost:8400/api/v1/search . 我想显示搜索localhost:8400/api/v1/search得到的json。 But I have no idea how. 但是我不知道如何。

I'm using the Elasticsearch Javascript Client 我正在使用Elasticsearch Javascript客户端

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 用于访问ElasticSearch数据库

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. 由于您将elasticsearch.search添加为路由处理程序,因此将使用一些参数来调用它。

Change the signature of the search method to search(req, res) . search方法的签名更改为search(req, res)
Then just call res.send(JSON.stringify(body)); 然后只需调用res.send(JSON.stringify(body));

See https://expressjs.com/en/4x/api.html#res for more details 有关更多详细信息,请参见https://expressjs.com/en/4x/api.html#res

Firstly, the route handlers for express routes always have (request, response, next) as it's parameters. 首先,快速路由的路由处理程序始终具有(request, response, next)作为其参数。 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. 您可以编写自己的路由处理程序并在其中调用elasticsearch.search ,而不是将elasticsearch.search方法作为路由处理程序传递,因此您仍然可以访问response对象。 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. 如果要将任何查询字符串参数从请求传递到搜索功能,也可以访问请求对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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