1

I am trying to return a value from a Cypress task, by the running of a function:

///// <reference types="cypress" />

/**
 * @type {Cypress.PluginConfig}
 */

var sqlite3 = require('sqlite3').verbose()
let db = new sqlite3.Database('/db/db.sqlite3', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    console.error(err.message);
  }
  console.log('Connected to the database.');
})

function getInvoiceNumberRowId() {
  db.each(`SELECT id FROM invoicerecord WHERE p_number = 7 and customer = 'John Doe'`, (err, row) => {
    if (err) {
      throw err;
    }
    console.log(`The invoice id is ${row.id}`)
    const row_id = row.id
    return row_id
  })
} 

module.exports = (on, config) => {
  on('task', {
   
     InvoiceNumberRowId() {
       return getInvoiceNumberRowId()
     }



//    }

  })
}

However, when I do cy.task('InvoiceNumberRowId') I get the following error message:

The task 'InvoiceNumberRowId' returned undefined. You must return a value, null, or a promise that resolves to a value or null to indicate that the task was handled.

I don't understand why I am getting this error because the function returns row_id.

The line console.log(`The invoice id is ${row.id}`) works just as expected so I know that row.id is defined.

I know this may be something to do with the Async nature of Javascript

Sorath
  • 543
  • 3
  • 10
  • 32
  • 1
    `return getInvoiceNumberRowId()` returns the result of calling `getInvoiceNumberRowId` ... and `getInvoiceNumberRowId` doesn't return anything (i.e. same as `return undefined` ... the `return row_id` is being returned in the `db.each` callback `(err, row) => {` – Jaromanda X Sep 03 '20 at 14:28
  • @JaromandaX How can I get the function to return `row_id` in this case? – Sorath Sep 03 '20 at 14:38
  • @Sorath read [this](https://stackoverflow.com/a/14220323/5648954) answer, it will explain how you can use callbacks or promises to retrieve the value you're after. As the row_id is only available asynchronously, you'll have to deal with it asynchronously also - meaning that you can't "bring it back" into synchronous code. – Nick Parsons Sep 03 '20 at 14:45
  • ... or if you want to do this synchronously you can see this [answer](https://stackoverflow.com/a/47963102/5648954), however, learning how to deal will asynchronous code like this is a good thing to know, as there won't always be a synchronous option ;) – Nick Parsons Sep 03 '20 at 14:51

0 Answers0