0

I am using nexus for my database purpose but I have a question which also generally applicable to JS/TS.

knex('cars').insert(cars).then(() => console.log("data inserted"))
    .catch((err) => { console.log(err); throw err })
    .finally(() => {
        knex.destroy();
    });

How can I create the above as a new Promise with reject or resolve to look like this

byID(id: string): Promise<TEntity> {
    return new Promise((resolve, reject) => {
      const result = pg(cars)
      .where({ 'id': id })
      //   .andWhere('age', '<', 18);
        .first();
        if (!result)
            return reject(new ModelNotFoundError('LMAO user not found')); 
        resolve(result)
    })
  }
King
  • 1,885
  • 3
  • 27
  • 84
  • 1
    Why do you want to use [the promise constructor antipattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it)? – VLAZ Dec 10 '20 at 06:29

2 Answers2

0

No need to wrap knex queries to promise constructor. You are probably trying to write somthing like this:

byID(id: string): Promise<TEntity> {
    return pg(cars).where({ 'id': id }).first()
        .then(result => {
          if (!result) {
            throw new ModelNotFoundError('LMAO user not found')); 
          }
          return result;
        });
     })
  }
Mikael Lepistö
  • 18,909
  • 3
  • 68
  • 70
-1

Not sure if this is what you're asking for but you can take advantage of async/await.

const result = await new Promise(async (resolve, reject) => {
  try {
    await knex('cars').insert(cars);
    console.log("data inserted");
  } catch (err) {
    console.log(err);
    reject(err);
  } finally {
    knex.destroy();
  }
  resolve();
})

You don't need to 'await' this promise, you can also .then it as well at that point. The main point I'm trying to make is that you can make the function in the Promise async.

Michael Bauer
  • 357
  • 1
  • 7
  • [Please, do ***not*** use async promise executors](https://stackoverflow.com/questions/43036229/is-it-an-anti-pattern-to-use-async-await-inside-of-a-new-promise-constructor) – VLAZ Dec 10 '20 at 16:58