I am converting my application to use async/await instead of callbacks for query request made on the backend. It's been going good so far, but I am on a bit of a snag. My page is hanging on getting a get route and not rendering the ejs page. The console from the server also displays,
(node:7036)
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: qryFindLocalID is not defined
(node:7036) .
[DEP0018] DeprecationWarning: Unhandled promise rejections are depreca
ted. In the future, promise rejections that are not handled will terminate the Nod
e.js process with a non-zero exit code.
Any help would be appreciated.
The code so far is,
router.get("/secure", async (req, res) => {
let user = req.session.passport.user;
try {
if (user.chkUserStatus) {
if (user.lWaterLabID == 0 || user.lWaterlabID == -9999) {
// in both cases sLabID is set to 0
// assign the correct value for sLabName
user.sLabName = user.lWaterLabID == 0 ? "Site Admin" : "Uber Admin";
} else {
let labName = await request.query(
"Some Query"
);
user.sLabName = labName[0].sLabName;
}
} else {
// Houston we've got a problem ...
// user.chkUserStatus is not truthy
req.flash("loginMessage", "User Status is invalid.");
res.redirect("/");
}
const qryFindLocalID = await request.query(
`Some Query`
);
if (user.lWaterLabID == 0) {
const listRecentReports = await request.query(Some Query);
} else {
const listRecentReports = await request.query(Some Query);
}
} catch (err) {
// ... error checks
}
res.render("secure/index", {
qryFindLocalID: qryFindLocalID,
user: user,
listRecentReports: listRecentReports
});
});
The error message talks about an unhandled promise, but that's just wrapping the actual error, which is: ReferenceError: qryFindLocalID is not defined.
So where are you using qryFindLocalID? Ah, right at the bottom in the res.render call.
res.render("secure/index", {
qryFindLocalID: qryFindLocalID,
user: user,
listRecentReports: listRecentReports
});
Now why is qryFindLocalID undefined here? You defined it above in the try-catch block. But there's your problem -- You used const, so qryFindLocalID only exists in the try-catch. Outside of that, it doesn't exist.
You can fix that by using var in the try-catch (var is scoped to the function), or define qryFindLocalID using let ABOVE the try-catch.
Related
I have this code, copied directly from the stripe website:
app.post('/createSubscription',async (req, res) => {
let r = (Math.random() + 1).toString(36).substring(7);
console.log(r);
const subscription = await stripe.subscriptions.create({
customer: 'cus_' + r,
items: [
{price: 'price_1InXJuIPT89VeZtCMeR3xQWf'},
],
});
})
however, when i run this code, it gives me an error in my console.
to show where the warning was created)
(node:38025) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict`
i am not sure exactly what this means, because I have never seen thsi error for stripe before? What am i doing wrong within my subscription funciotn?
You should try/catch any async function which may throw an error. For example:
let subscription;
try {
subscription = await stripe.subscriptions.create({
customer: 'cus_' + r,
items: [
{ price: 'price_1InXJuIPT89VeZtCMeR3xQWf' },
],
});
} catch (e) {
console.error(e);
// Do something about the fact that you encountered an error, example:
return res.status(500).send('Internal Error');
}
// Do stuff with subscription
This should at least log your error and prevent it from crashing the process. Once you can see the actual error causing the problem then you will be able to reference stripe's documentation.
I was following this tutorial on how to make a discord bot, everything was working fine until 33:32 where he added the giphy stuff i had already installed giphy sdk/api, created an application, but after he made the search statement he said you can console log it so i did it, and there were some gif results coming out, which returned undefined on my console(i dunno why), then he added some math stuff, which i also did, then at the point where he added the messaging part where he also added this code files:[responseFinal.images.fixed_height.url] which then returned this on my console
(node:3136) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'images' of undefined
at D:\Discord bots\Oboto v2.0\index.js:24:61
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:3136) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:3136) [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.
and this confused the flip outta me, then i picked an alt approach, instead of doing giphy.search i did
giphy.random with the same arguments, removed the math stuff and console.log(response)the response and guess what it actually gave me a single gif!(in the console of course) then i implemented to my files:[]statement aaaaand it returned the same thing (cannot read property 'images' of undefined) im also kinda new to discord.js and javascript, also here is my entire code,
const Discord = require('discord.js');
const { prefix, token, giphyToken } = require('./config.json');
const client = new Discord.Client();
var GphApiClient = require('giphy-js-sdk-core')
giphy = GphApiClient(giphyToken)
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])){
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
member.kick().then((member) =>{
giphy.random('gifs', {'q':'fail'})
.then((response) => {
console.log(response);
message.channel.send(":wave:",{files:[response.images.fixed_height.url]});
})
})
}
}
})
client.login(token);
cannot read property 'images' of undefined, this means you are trying to access a null object. Same as null pointer exception in java. It means your response is null.
And you are also getting UnhandledPromiseRejectionWarning which means your promise is throwing error which you are not catching anywhere. You can catch your error like this
member.kick().then((member) =>{
giphy.random('gifs', {'q':'fail'})
.then((response) => {
console.log(response);
message.channel.send(":wave:",{files:[response.images.fixed_height.url]});
}).catch(e => { console.error(e}) }
}).catch(e => { console.error(e) }
Now you can see what error you are getting. You can also use try catch approach with async await.
THIS CODE IS FIXED BY ME :D
Discord Bot - Kick member with Giphy
IM NOT A PROFESSIONAL AT ALL.
You can also add this giphy to new member notice.
const Discord = require('discord.js');
const { prefix, token, giphyToken } = require('./config.json');
const bot = new Discord.Client();
var GphApiClient = require('giphy-js-sdk-core');
bot.giphy = GphApiClient(giphyToken);
bot.on('message', (message) => {
if (message.member.hasPermission(['KICK_MEMBER', 'BAN_MEMBERS'])) {
//console.log(message.content);
if (message.content.startsWith(`${prefix}kick`)) {
//message.channel.send("kick")
let member = message.mentions.members.first();
member.kick().then((member) => {
bot.giphy.search('gifs', { q: 'fail' }).then((response) => {
var totalResponses = response.data.length;
var responseIndex = Math.floor(Math.random() * 10 + 1) % totalResponses;
var responseFinal = response.data[responseIndex];
message.channel.send(':wave: ' + member.displayName + ' has been kicked!',{
files: [responseFinal.images.fixed_height.url]
}
)
})
})
}
}
});
bot.login(token);
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 know this is not the most beautiful code, but due to legacy issues, I need to stick to this workflow.
The problem is that I am not able to bubble up any exceptions that might occur in the heart of the returned promise.
The code is designed that both the reject and resolve return valid data. So, if you change the const CONDITION to 0.4, we will be getting a rejection. If the value of const CONDITION stays at 0.6, we will be getting a resolution. This works so far.
However, in cases where we have structural failures, such as in the example below where we try to pass a wrong variable name into the rejection:
let reasoxxxx = '__FAILED__';
reject({error: reason, data: output});
I am not able to invoke a throw to bubble up the error. For that reason, I am getting the usual ugly message and I cannot bubble up a proper exception:
Exchange request was rejected due to error(s).
(node:224) UnhandledPromiseRejectionWarning: ReferenceError: reason is not defined
(node:224) 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:224) [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.
Any ideas? The code snipped should work.
function fakeFetch() {
// Promisify the request.
return new Promise((resolve, reject) => {
// Emulate an asynchroneous fetch.
setTimeout(() => {
let result = 0.4; // Change to 0.4 to trigger a failed fetch.
if (result < 0.5) {;
reject('__FAIL__');
} else {
resolve({name: 'apple', price: '1234.12', time: 1549926859970});
}
}, 2000);
});
}
async function sendExchangeRequest(id, pair, symbols, callback)
{
let err, result
await fakeFetch().then((output) => { result = output }).catch((error) => {err = error})
if(err){
result = 'None'
}else{
err = 'None'
}
callback(err, result)
}
async function fetchExchangeData(id, pair, symbols) {
// Promisify the request.
try {
return new Promise((resolve, reject) => {
try {
// Send the request.
sendExchangeRequest(id, pair, symbols, ((err, output) => {
try{
if(err){
// Soft Failure
console.log('Exchange request was rejected due to error(s).');
reject({error: err, data: output});
}else{
// Success
console.log('Exchange request was successful.');
resolve({error: err, data: output});
}
} catch(error) {
throw error;
}
}));
} catch(error) {
console.log('---\n', error, '\n---');
throw error;
}
});
} catch(error) {
// Bubble up the error?
console.log('+++\n', error, '\n+++');
throw error;
}
}
(async () => {
await fetchExchangeData('myid', 'MYPAIR', 'mySymbol')
.then((result) => console.log(result))
.catch((failure) => console.log(failure))
})();
--- EDIT (01) ---
I have updated my example snipped to include a fake API call. I hope this makes my question a bit more clear.
I think you're not understanding the concept of async functions. Your first try/catch in fetchExchangeData do essentially nothing, and there is nothing async in it. The try/catch inside the initial promise, is also almost useless, as I'm sure most/all issues with sendExchangeRequest will likely be dealt with the error handler function (err). As for the try/catch blocks, you shouldn't throw errors inside the promise, you should instead reject the error (Which will bubble it up). Only try/catch if you're in an async function, and NOT using callbacks.
function fetchExchangeData(id, pair, symbols) {
// Promisify the request.
return new Promise((resolve, reject) => {
try {
// Send the request.
sendExchangeRequest(id, pair, symbols, ((err, output) => {
try{
if(err){
// Soft Failure
console.log('Exchange request was rejected due to error(s).');
let reason = '__FAILED__';
reject({error: reason, data: output});
}else{
// Success
console.log('Exchange request was successful.');
resolve({error: '__NONE__', data: output});
}
} catch(error) {
reject(error);
}
}));
} catch(error) {
console.log('---\n', error, '\n---');
reject(error);
}
});
}
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'));
}
}