![](/img/trans.png)
[英]How to create a function returning a promise that resolves after inner promise resolves
[英]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.