簡體   English   中英

Promise解決后,在“然后”中發送響應

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

我想顯示搜索localhost:8400/api/v1/search得到的json。 但是我不知道如何。

我正在使用Elasticsearch Javascript客戶端

我的路線:

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

const router = express.Router();

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

用於訪問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;

由於您將elasticsearch.search添加為路由處理程序,因此將使用一些參數來調用它。

search方法的簽名更改為search(req, res)
然后只需調用res.send(JSON.stringify(body));

有關更多詳細信息,請參見https://expressjs.com/en/4x/api.html#res

首先,快速路由的路由處理程序始終具有(request, response, next)作為其參數。 您可以使用響應對象將數據發送回客戶端。

您可以編寫自己的路由處理程序並在其中調用elasticsearch.search ,而不是將elasticsearch.search方法作為路由處理程序傳遞,因此您仍然可以訪問response對象。 例如:

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

並像這樣構造您的搜索功能:

const elasticsearch = {

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

這樣,您就可以將查詢彈性和處理請求的問題分開。 如果要將任何查詢字符串參數從請求傳遞到搜索功能,也可以訪問請求對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM