Node.js 创建一个HAPI路由先决条件,以从RESTAPI获取一些值

Node.js 创建一个HAPI路由先决条件,以从RESTAPI获取一些值,node.js,hapijs,Node.js,Hapijs,如何创建路由先决条件以从RESTAPI获得一些价值?如何实现getCount函数以等待API响应并在路由处理程序函数中使用它?(请注意,我使用的是Hapi 8.3.1) 您似乎希望在代码继续之前等待HTTP请求完成?在这种情况下,您将需要使getCount成为一个异步函数,并等待get请求。您还应该使用fetch()而不是http.get()。所以,你最终会得到这样的结果: server.route({ method: 'GET', path: '/products',

如何创建路由先决条件以从RESTAPI获得一些价值?如何实现getCount函数以等待API响应并在路由处理程序函数中使用它?(请注意,我使用的是Hapi 8.3.1)


您似乎希望在代码继续之前等待HTTP请求完成?在这种情况下,您将需要使getCount成为一个异步函数,并等待get请求。您还应该使用fetch()而不是http.get()。所以,你最终会得到这样的结果:

server.route({
    method: 'GET',
    path: '/products',
    config: {
        state: {
            failAction: 'ignore'
        },
        pre:[{method:getCount, assign: 'count'}],
        handler: function (request, reply) {

            console.log(request.pre.count);

            reply({products}).code(200);
        }
    }
});

async function getCount(request, reply){
    let count = await fetch('/products/count/');
    return count;
}
这将等待请求完成,然后返回值。如果您的节点版本不支持async/await,也可以使用.then()并承诺这样做。使用它将产生如下代码:

server.route({
    method: 'GET',
    path: '/products',
    config: {
        state: {
            failAction: 'ignore'
        },
        pre:[{method:getCount, assign: 'count'}],
        handler: function (request, reply) {

            console.log(request.pre.count);

            reply({products}).code(200);
        }
    }
});

function getCount(request, reply){
    return new Promise(function (resolve, reject) {
      fetch('/products/count/').then(function(result) {
        resolve(result); 
      }).catch(function (err) {
        reject(err);
      });
    });
}
server.route({
    method: 'GET',
    path: '/products',
    config: {
        state: {
            failAction: 'ignore'
        },
        pre:[{method:getCount, assign: 'count'}],
        handler: function (request, reply) {

            console.log(request.pre.count);

            reply({products}).code(200);
        }
    }
});

function getCount(request, reply){
    return new Promise(function (resolve, reject) {
      fetch('/products/count/').then(function(result) {
        resolve(result); 
      }).catch(function (err) {
        reject(err);
      });
    });
}