user11751709
user11751709

Reputation:

TypeError: Cannot read property 'id' of undefined & bad variable log

I have 2 problems: I'm trying to insert Promise.all in my code, I needed Promise.all for asynchronous database calls.

The first problem is that by using the code I will post below (code A), when I log the "idArticolo" variable, in console the result is all the code of the "getIdArticolo ()" function, (I mean that it just logs me in the written code to execute, and not the value of the variable I want), maybe I don't have to use the getIdArticolo function but a variable?

I tried using the variable var getIdArticolo = new Promise (code B) and it gives me another error:

"TypeError: Cannot read property 'id' of undefined", referring to the code "resolve (result [0] .id ); "," result "is undefined!

Why?

In practice it is the exact same code except that one is in one function and the other is the assignment of a variable. Obviously I use either the A code or the B code, commenting on the code I don't want to execute.

ALL THE CODE:

var mysql = require('mysql')
var http = require('http')
var url = require('url');
var express = require("express");
var cors = require('cors')

var app = express();

var sql = "";
var connection = mysql.createConnection({
      host: '127.0.0.1',
      user: 'andrea',
      password: 'password',
      database: 'spesa'
});
connection.connect();

function LinkMysql() {

    var data = '';

    return new Promise(function(resolve,reject) {
        connection.query(sql, function(err, result) {

            if(err)
                console.log("error: " + err);

            resolve(result);
        });

    });

}  

var idArticolo;
var idCategoria;
var nuovoId;

var articolo, costo, quantita, negozio, data;

app.use(cors());

app.get('/inserisciDati',function(request, response){

    console.log("/inserisciDati");
    /*
    console.log("/inserisciDati");
    console.log("articolo="+request.query.articolo);
    console.log("costo="+request.query.costo);
    console.log("quantita="+request.query.quantita);
    console.log("negozio="+request.query.negozio);
    console.log("data="+request.query.data);
    */
    articolo = request.query.articolo;
    costo = request.query.costo;
    quantita = request.query.quantita;
    negozio = request.query.negozio;
    data = request.query.data;

    //INSERIRE RISPOSTA ALLA PAGINA HTML CON ERRORE SE C'È

    //recuperare gli id dell' articolo e del negozio, l' id categoria dell'articolo e il nuovo id del registro

    getValues();

    //INSERIRE I DATI IN TABLLA MYSQL

});

function getValues(){

    Promise.all([getIdArticolo, getIdCategoria, getLastId]).then(function(values){

        idArticolo = values[0];
        idCategoria = values[1];
        nuovoId = values[2];

        console.log("idArticolo="+idArticolo);

        sql="INSERT INTO registro VALUES ('" + nuovoId + "','" + articolo + "','" + idCategoria + 
        "','" + idArticolo + "','" + costo + "','" + quantita + 
        "','" + negozio + "','" + data + "')";

        //console.log("sql="+sql);

    });

}

var getIdArticolo = new Promise(function(resolve, reject){

    sql = "SELECT id FROM articoli WHERE articolo = '" + articolo + "'";

    connection.query(sql, function(err, result) {

        if(err)
            console.log("error: " + err);

        resolve(result[0].id);

    });

});

function getIdArticolo(){

    return new Promise(function(resolve,reject) {

        sql = "SELECT id FROM articoli WHERE articolo = '" + articolo + "'";

        connection.query(sql, function(err, result) {

            if(err)
                console.log("error: " + err);

            resolve(result[0].id);

        });

    });

}

function getIdCategoria(){

    return new Promise(function(resolve, reject){

        sql = "SELECT id_categoria FROM articoli WHERE articolo = '" + articolo + "'";

        connection.query(sql, function(err, result) {

            if(err)
                console.log("error: " + err);

          resolve(result[0].id_categoria);

        });

    });

}

function getLastId(){

    return new Promise(function(resolve, reject){

        sql = "SELECT id FROM registro ORDER BY id DESC LIMIT 1";

        connection.query(sql, function(err, result) {
            if(err)
                console.log("error: " + err);

            resolve(result[0].id);

        });

    });

}

app.get('/getArticoli', function(request, response){

    console.log("/getArticoli");
    response.setHeader("Access-Control-Allow-Origin", "*"); 
    response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
    response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    response.setHeader("X-Powered-By",' 3.2.1');
    response.setHeader("Content-Type", "application/json");

    sql = 'SELECT articolo FROM articoli ORDER BY articolo ASC';

    LinkMysql().then(function(val) {

        response.writeHead(200, {'content-Type': 'text/plain; charset=utf-8'});
        response.end(JSON.stringify(val));

    });

});

app.get('/getNegozi', function(request, response){

    console.log("/getNegozi");
    response.setHeader("Access-Control-Allow-Origin", "*"); 
    response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
    response.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    response.setHeader("X-Powered-By",' 3.2.1');
    response.setHeader("Content-Type", "application/json");

    sql = 'SELECT negozio FROM negozi ORDER BY negozio ASC';

    LinkMysql().then(function(val) {

        response.writeHead(200, {'content-Type': 'text/plain; charset=utf-8'});
        response.end(JSON.stringify(val));

    });

});

app.listen(8080);

EXTRACT OF CODE A:

function getIdArticolo(){

    return new Promise(function(resolve,reject) {

        sql = "SELECT id FROM articoli WHERE articolo = '" + articolo + "'";

        connection.query(sql, function(err, result) {

            if(err)
                console.log("error: " + err);

            resolve(result[0].id);

        });

    });

}

EXTRACT OF CODE B:

var getIdArticolo = new Promise(function(resolve, reject){

sql = "SELECT id FROM articoli WHERE articolo = '" + articolo + "'";

    connection.query(sql, function(err, result) {

        if(err)
            console.log("error: " + err);

        resolve(result[0].id);

    });

});

LOG OF CODE A

Thanks!

Upvotes: 2

Views: 531

Answers (1)

nicholascm
nicholascm

Reputation: 641

There seem to be a couple issues with either approach:

It looks like you have forgotten to invoke the functions which return the promises.

For example: Code A is getIdArticolo that must be invoked getIdArticolo() to return a promise that you can wait on inside of a Promise.all statement.


Promise.all([getIdArticolo(), getIdCategoria()]).then(result => { 


});

Also, remember that when declaring something as a variable as in var getIdArticolo = new Promise() the variable declaration is hoisted.

Upvotes: 2

Related Questions