Как вернуть результат обратной функции в контроллер loopback 4 - PullRequest
0 голосов
/ 30 сентября 2019

Я пытаюсь выполнить функцию поиска в объекте TypeORM внутри моего контроллера loopback4.

Проблема в том, что в соответствии с документацией TypeORM я выполнил запрос в функции обратного вызова then, присоединенной к функции createConnection. Таким образом, результат вызова 'findOne' выходит за рамки метода контроллера

//this is the controller method signature
async findById(@param.path.number('id') id: number): Promise<Pratica> {

    createConnection({
      type: 'oracle',
      host: '10.64.2.226',
      port: 1521,
      sid: 'NPRA02S',
      username: 'sua03e',
      password: 'iniziale',
      entities: [
        Pratica
      ],
      logging: true
    }).then(async connection => {
      let praticaRepository = connection.getRepository(Pratica);

      // I have to return this as a result parameter in the controller
      let pratica = await praticaRepository.findOne({ protocolloaci: id });

    }).catch(error => console.log(error));

  }

. Я пробовал также следующее, но я бы знал, как управлять этим без асинхронной / await * 1006. *

//this is the controller method signature
async findById(@param.path.number('id') id: number): Promise<Pratica> {

    let connection = await createConnection({
      type: 'oracle',
      host: '10.64.2.226',
      port: 1521,
      sid: 'NPRA02S',
      username: 'sua03e',
      password: 'iniziale',
      entities: [
        Pratica
      ],
      logging: true
    })

    let praticaRepository = connection.getRepository(Pratica);

    return await praticaRepository.findOne({ protocolloaci: id }) || new Pratica;

  }

Заранее спасибо

1 Ответ

1 голос
/ 30 сентября 2019

Попробуйте код ниже

async findById(@param.path.number('id') id: number): Promise<Pratica> {

        return new Promise( (resolve)=>{

            createConnection({
              type: 'oracle',
              host: '10.64.2.226',
              port: 1521,
              sid: 'NPRA02S',
              username: 'sua03e',
              password: 'iniziale',
              entities: [
                Pratica
              ],
              logging: true
            }).then(async connection => {
              let praticaRepository = connection.getRepository(Pratica);

              // I have to return this as a result parameter in the controller
              const pratica = await praticaRepository.findOne({ protocolloaci: id });
              resolve(pratica); // return using resolve
            }).catch(error => console.log(error));
        });
}
...