NodeJS Elasticsearch搜索返回promise而不是值 [英] NodeJS Elasticsearch search returns promise instead of values

查看:81
本文介绍了NodeJS Elasticsearch搜索返回promise而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Node服务器内部向Elasticsearch发送了一个请求.这很完美,除了我总是得到一个承诺而不是结果.

I made a request inside my Node server to Elasticsearch. This is working perfect, except that I always get a promise returned instead of the results.

当我用控制台记录结果时,它们看起来很完美,但是当我返回它们时,我什么也没得到,也没有希望.

When I console log the results they look perfect, but when I return them I either get nothing or a promise.

有人可以告诉我从Elasticsearch检索和处理数据的正确方法吗?

Can someone tell me the proper way to retrieve, and handle the data from Elasticsearch?

我正在使用带有节点服务器和官方Elasticsearch软件包的VueJS.

I am using VueJS with a Node server and the official Elasticsearch package.

    function getNewTest(client)
    {
        client.search({
            index: 'myIndex',
        }).then(function(resp) {

            return resp.hits.hits;

        }, function(err) {

            console.trace(err.message);

        });
    }

    let tests = getNewTest(client);
    console.log(tests);

    # Output: Promise { <pending> }

如建议,我尝试了两个代码,都没有工作.我更改了自己的代码,现在它向我返回了未定义".

As suggested I tried both codes, both didnt work. I changed my own code, now it returns an "undefined" to me.

getNewTest(client).then(function (response) {
           console.log(response);
        });

将向我返回未定义".我将功能更改为此:

will return "undefined" to me. I changed my function to this:

async function getNewTest(client)
{
    await client.search({
        index: 'myIndex',
    }).then(function(resp) {

        console.log(resp.hits.hits, 'returned');
        return resp.hits.hits;

    }, function(err) {

        console.trace(err.message);

    });
}

我什么时候做

let test = getNewTest(client);

它给了我一个诺言.

推荐答案

(async () => {

let tests = await getNewTest(client);
console.log(tests);
})();

您正在进行数据库调用,因此主线程变为空闲并开始执行下一行.代码需要等到诺言解决之后,再执行下一行.

You are making a db call, so the main thread becomes free and start executing the next line. The code needs to wait till the promise is resolved and then execute the next line.

或者,如果您不想使用异步等待,则可以在下面使用此代码-

Or if you dont want to use async await, you can use this code below -

async function getNewTest(client) {
    client.search({
        index: 'myIndex',
    }).then(function (resp) {

        return resp.hits.hits;

    }, function (err) {

        console.trace(err.message);

    });
}


getNewTest(client).then(result => {
    console.log(result);
});

这篇关于NodeJS Elasticsearch搜索返回promise而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆