Search code examples
node.jsreact-nativeexpresspromiserequest-promise

Promise not returning resolve from express app.get Nodejs


I'm trying to return a resolve or reject depending on if the promise was successful or not. I can't seem to figure out why this isn't returning the response. All I get from my promise is [object Object]. This is what I get in response.

Here's the code:

app.get('/', (req,res) => {
    return new Promise((resolve,reject) => {
        var sql = "INSERT INTO usersinfo (firstname,lastname,email,number,latitude,longitude) VALUES(?,?,?,?,?,?)";
        conn.query(sql,[fname,lname,email,num,req.query.latitude,req.query.longitude], (err,result) => {
            if (err) {
                res.send('error')
                console.log(err,'there has been an error')
                reject('There was an error')
                return
            }else{
                console.log('inserted')
                resolve({ success:'true' })
            }
            res.end()
        })
    })
})

Where I'm fetching the url:

const res = await fetch(`http://MYIPADDRESS?latitude=${latitude}&longitude=${longitude}`)
                console.log(res)

I don't seem to get what's wrong. And if I attach the then((response) => console.log(response)) method I get an error in the expo app saying There was an error sending log messages to your development environment PrettyFormatPluginError:value.hasOwnProperty is not a function. (In 'value.hasOwnProperty('tag')','value.hasOwnProperty is undefined)


Solution

  • You don't need to create a promise. The send method can be called asynchronously -- when the response is ready:

    app.get('/', (req,res) => {
        var sql = "INSERT INTO usersinfo (firstname,lastname,email,number,latitude,longitude) VALUES(?,?,?,?,?,?)";
        conn.query(sql,[fname,lname,email,num,req.query.latitude,req.query.longitude], (err,result) => {
            if (err) {
                res.send('error');
                console.log(err,'there has been an error');
            } else {
                res.send({ success:'true' }); // <---
                console.log('inserted');
            }
        });
    });
    

    NB: also, there is no need to call res.end() as res.send() already implies that.

    On the client side you'll have to await the JSON content to be generated:

    const response = await fetch(`http://MYIPADDRESS?latitude=${latitude}&longitude=${longitude}`);
    const result = await response.json(); // <---
    console.log(result);