const { GraphQLServer } = require('graphql-yoga');
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/test1");
const Todo = mongoose.model('Todo',{
text: String,
complete: Boolean
});
const typeDefs = `
type Query {
hello(name: String): String!
}
type Todo{
id: ID!
text: String!
complete: Boolean!
}
type Mutation{
createTodo(text:String!): Todo
}
`
const resolvers = {
Query: {
hello: (_, { name }) => `Hello ${name || 'World'}`,
},
Mutation:{
createTodo: async (_,{ text }) => {
const todo = new Todo({text, complete: false});
await todo.save();
return todo;
}
}
};
const server = new GraphQLServer({ typeDefs, resolvers })
mongoose.connection.once("open", function() {
server.start(() => console.log('Server is running on localhost:4000'))
});
Hello I'm new to node js and mongoDB. I'm trying to start my server but it's not starting. Every time it shows a error like this:
(node:17896) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing
inside of an async function without a catch block, or by rejecting a promise
which was not handled with .catch(). (rejection id: 1)
(node:17896) [DEP0018] DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.
Every time this is showing some promise error.Can anyone please help me to debug this program. I m a beginner. I don't know much of it. But as per my understanding, I have written correct code only.
Probably your save function throws an arrow which you don't handle it!
you can solve this issue with one of these ways:
GraphQL handles promise by itself, so this would give you same result:
createTodo: (_,{ text }) => {
const todo = new Todo({text, complete: false});
return todo.save();
}
using try catch would give you better error handling:
createTodo: async (_,{ text }) => {
const todo = new Todo({text, complete: false});
try {
await todo.save();
return todo;
} catch(err) {
\\ do something with error
console.error('error=>', err);
return null;
}
}
Related
Comment: I'm sure this is quite simple, but I can't seem to figure out the right combination of async/await try/catch.
Senario: I'm reading DHT22 temp/humidity sensor that may return an error, in which case I want to return a default value. I want getHumidity() to wait for reading and return value or default value. And then printConditions() simple calls and doesn't execute until it receives a response.
Question: Is it possible have delay in getHumidity(), and other calls are unaware its async, cause I have a lot of variations of printConditions()?
const printConditions = () => `Current Humidity is: ${getHumidity().fixed(2)}`;
//Both Attempts return: Current Humidity is NaN%
//Which I believe implies it is not waiting nor default value of 75.0.
//Attempt 1
const getHumidity = async () => {
try { return await sensor.read(22, sensorPin).humidity; }
catch (error) {console.log(error); return 75.0; }
}
try/catch block returns this error: ??? : (node:1368) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
//Attempt 2:
const getHumidity = async () => {
return await sensor.read(22, sensorPin)
.then(value=>{ return value.humidity;})
.catch(error=>{console.log(error); return 75.0;});
}
const printConditions = async () => {
let reading;
try {
reading = await sensor.read(22, sensorPin).humidity;
}
catch(error) {
console.log(error);
reading = 75.0;
}
finally {
console.log(`Current Humidity is: ${reading.fixed(2)}`);
}
}
did you try adding an await when you call the asynchronus function?
const printConditions = async () => `Current Humidity is: ${await getHumidity().fixed(2)}`;
I'm trying to create an auxiliar method to use inside the same controller:
module.exports = {
async update(req, res) {
// code here...
// method call
this.verifyItemInStock()
// more code here ...
},
// method declaration
verifyItemInStock (itemId) {
// more code...
}
}
but I'm getting the following error:
(node:31904) UnhandledPromiseRejectionWarning: ReferenceError:
verifyItemInStock is not defined
at update (/home/netogerbi/workspaces/zombieresistance/zombieresistance/app/controllers/trade.controller.js:34:5)
(node:31904) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an async
function without a catch block, or by rejecting a promise which was
not handled with .catch(). (rejection id: 1) (node:31904) [DEP0018]
DeprecationWarning: Unhandled promise rejections are deprecated. In
the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.
Remove the this and make it more readable:
// method declaration
const verifyItemInStock = itemId => {
// more code...
}
const update = async (req, res) => {
// code here...
// method call
verifyItemInStock()
// more code here ...
}
module.exports = {
update,
verifyItemInStock,
}
Also, the consumer of the promise should have a catch:
import { update } from './my-module';
update(req, res).then(...).catch(...)
// or
try {
const resolved = await update(req, res);
// consume the resolved value
} catch (e) {
// exception handling
}
I resolved by the following:
const update = async (req, res) => {
// auxiliar method declaration
verifyItemInStock = itemId => {
// code...
}
// ...
// method call
const hasItems = verifyItemInStock(id)
}
Thank you very much...
I am writing a simple Node/Express/React/Postgres application and I'm using the pg package to interface with my Postgres Server.
I require three tables, table1, table2, and table3. table2 has a foreign key in table1 and table3 has a foreign key in table 2, so the order that I need to create the tables in is: table1 then table2 then table3.
I am attempting to use promises to enforce this order in my asynchronous table creation calls. I've generally followed Brian Carlson's suggested Project Structure, but clearly I'm doing something wrong.
Here are the simplified, relevant files from my project:
db.js:
const { Pool } = require('pg');
// Create pool connection to database
const pool = new Pool({
user: XXXX,
host: XXXX,
database: XXXX,
password: XXXX,
port: XXXX
});
// Pool emitters
pool.on('connect', () => {
console.log('Connected a client to the database');
});
pool.on('remove', () => {
console.log('Disconnected a client from the database');
});
pool.on('error', (err, client) => {
console.error('Unexpected error on idle client', err);
process.exit(-1);
});
// This structure taken from Brian Carlson's pg API Documentation
// https://node-postgres.com/guides/project-structure
module.exports = {
query: (text, params) => {
console.log('Making a query!');
return pool.query(text, params);
}
};
table_scripts.js:
const db = require('../db');
const Database_Scripts = {
create_table_1: () => {
const create_table_1_query = {
text: `CREATE TABLE IF NOT EXISTS
public.table_1
(
id smallserial,
name text NOT NULL,
PRIMARY KEY (id)
);`
};
return db.query(create_table_1_query);
},
create_table_2: () => {
const create_table_2_query = {
text: `CREATE TABLE IF NOT EXISTS
public.table_2
(
id smallserial,
table_1_id integer NOT NULL REFERENCES public.table_1(id),
name text NOT NULL,
PRIMARY KEY (id)
);`
};
return db.query(create_table_2_query);
},
create_projects_table: () => {
const create_table_3_query = {
text: `
CREATE TABLE IF NOT EXISTS
public.table_3
(
id smallserial,
table_3_id integer NOT NULL REFERENCES public.table_2(id),
name text NOT NULL,
PRIMARY KEY (id)
);`
};
return db.query(create_table_3_query);
}
};
module.exports = Database_Scripts;
create_tables.js:
const Table_Scripts = require('./table_scripts');
Table_Scripts.create_table_1()
.then(Table_Scripts.create_table_2())
.then(Table_Scripts.create_table_3())
.catch(error => console.log(error.stack));
package.json:
{
"name": "app",
"version": "0.0.0",
"scripts": {
"start": "nodemon ./bin/www",
"create_tables": "node ./database/scripts/create_tables.js"
}
}
When I run my create_tables script (npm run-script create_tables), I get the following (sanitized) errors:
Connected a client to the database
Connected a client to the database
Connected a client to the database
Disconnected a client from the database
(node:13444) UnhandledPromiseRejectionWarning: error: relation "public.table_1" does not exist
(node:13444) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a
catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13444) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Disconnected a client from the database
(node:13444) UnhandledPromiseRejectionWarning: error: relation "public.table_2" does not exist
(node:13444) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a
catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
Disconnected a client from the database
I've been able to get this script to work converting the functions to async functions, however, I'd really like to understand what I'm doing wrong here.
Your problem seems to be that you're concurrently creating the tables despite explicitly needing to do the opposite.
According to the documentation, pool.query() returns a promise if not provided a callback function as a third argument. You need to wait for each of your db.query() promises to be resolved. Thus it'll wait for the first table to be created, then create the second one and finally the third one.
I would recommend using the async/await syntax
async function createTables () {
try {
const create_table_1_query = {
text: `yourQuery1`
};
// awaits for the first table to be created
await db.query(create_table_1_query);
const create_table_2_query = {
text: `yourQuery2`
};
// awaits for the second table to be created
await db.query(create_table_2_query);
const create_table_3_query = {
text: `yourQuery3`
};
// awaits for the third table to be created
await db.query(create_table_3_query);
} catch (e) {
console.error(e.stack);
}
}
module.exports.createTables = createTables;
You can then call await createTables();
when I running my project, I get the error:
(node:5795) UnhandledPromiseRejectionWarning: Error: reply interface called twice
at Object.exports.assert (/Users/labikemmy/Downloads/React-Native-FriendChat/api/node_modules/hoek/lib/index.js:736:11)
at Function.internals.response (/Users/labikemmy/Downloads/React-Native-FriendChat/api/node_modules/hapi/lib/reply.js:164:10)
at bound (domain.js:301:14)
at Function.runBound (domain.js:314:12)
at reply (/Users/labikemmy/Downloads/React-Native-FriendChat/api/node_modules/hapi/lib/reply.js:72:22)
at bound (domain.js:301:14)
at runBound (domain.js:314:12)
at result.then (/Users/labikemmy/Downloads/React-Native-FriendChat/api/node_modules/hapi/lib/handler.js:105:36)
at <anonymous>
at process._tickDomainCallback (internal/process/next_tick.js:228:7)
(node:5795) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:5795) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
null
I don't know it is bug or my code error? I'm screen hapi.js issues, and someone said the error is bug, another said 'reply() times is limit in same request'? if it is limited, how to change the code at below?
```
export default async function (request, reply) {
if (request.auth.credentials.email !== request.payload.email) {
await User.findOne({ email: request.auth.credentials.email }).then(
(user) => {
if (user) {
User.findOne({ email: request.payload.email }).then(
(friend) => {
if (friend) {
const stringId = `${friend._id}`;
const friendExists = user.friends.filter(f => `${f}` === stringId).length > 0;
if (!friendExists) {
user.friends.push(friend);
user.save();
reply({ friend: { fullName: friend.fullName, _id: friend._id } });
} else {
reply(Boom.conflict('You have added already this friend'));
}
} else {
reply(Boom.notFound(`Friend ${request.payload.email} doesn't exist`));
}
},
);
} else {
reply(Boom.notFound('Cannot find user'));
}
},
);
} else {
reply(Boom.conflict('Cannot add yourself as a friend'));
}
}
Hapi#16.4.1
Do you have any other plugins or lifecycle hooks like onPreHandler or something? Maybe there is some point your code that throws this error because you (or your code somehow) are calling reply interface before your actual response.
Also, I refactored your code. You are already utilizing JavaScript async interface, so you don't need to put "then" calls to your promises.
Try this and watch that what will come out:
export default async function (request, reply) {
if (request.auth.credentials.email === request.payload.email) {
return reply(Boom.conflict('Cannot add yourself as a friend'))
}
// I belive this is mongoose model
const user = await User.findOne({email: request.auth.credentials.email}).exec();
if (!user) {
return reply(Boom.notFound('Cannot find user'));
}
const friend = await User.findOne({email: request.payload.email}).exec();
if (!friend) {
return reply(Boom.notFound(`Friend ${request.payload.email} doesn't exist`));
}
const stringId = `${friend._id}`;
const friendExists = user.friends.filter(f => `${f}` === stringId).length > 0;
if (!friendExists) {
// hmmm shouldn't it be friend._id? user.friends.push(friend._id.toString());
user.friends.push(friend);
// better use this statement
// ref: http://mongoosejs.com/docs/api.html#document_Document-markModified
user.markModified('friends');
await user.save();
return reply({friend: {fullName: friend.fullName, _id: friend._id}});
} else {
return reply(Boom.conflict('You have added already this friend'));
}
}
I get these cryptic lines here:
DEBUG: Mongoose connected (node:5983)
UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): TypeError: Cannot read property 'then' of undefined
(node:5983) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.
How can I get useful debugging information so I don't have to guess where the exact issue is?
I believe it is somewhere in this file:
const mongoose = require('mongoose');
const helper = require('../config/helper');
const schema = require('./Schemas')
mongoose.connect(helper.getMongoose()).then(
() => {
console.log('DEBUG: Mongoose connected')
mongooseConnected();
},
(err) => {
console.log('DEBUG: Mongoose did not connect')
}
);
function mongooseConnected () {
makeSchema( schema.User,
{ id_google: '1',
type: 'person',
timestamp: Date.now()
});
}
function makeSchema (Schema, dataObj) {
const Class = mongoose.model('Class', Schema);
const Instance = new Class(dataObj);
Instance.save((err, results)=>{
if (err) {
return console.error(err);
}
}).then(() => {
console.log('Saved Successfully')
});
}
In your case you are providing a callback to your save function, this way mongoose will not return a Promise:
Instance.save((err, results)=>{
if (err) {
return console.error(err);
}
console.log('Saved Successfully')
})
If you still want to use Promise then you don't have to pass a callback function:
Instance.save().then(() => {
console.log('Saved Successfully')
}).catch(err => {
return console.error(err);
});
In general an unhandled Promise rejection means that you're missing a catch method to deal with the error. Simply including .then() after returning a promise only deals with the code if it runs successfully, whereas including a .catch block will skip .then and only run .catch, with the error as a callback when an error occurs while executing the code which returns the promise.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
myModel.save()
.then(() => {
console.log('Saved');
})
.catch(err => {
console.log(err);
}