Search code examples
javascripttypescriptknex.js

creating new Promise instead of using then() JS


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)
    })
  }

Solution

  • 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.