In the following code obj1 and obj2 are arrays.
if(obj2.length != 0) {
func(obj1, obj2);
}
//execute func only when obj2 is not empty
var func = (obj1, obj2) => {
const Channel = obj2.reduce((acc, curVal) => {
obj1.forEach((item) => {
if (curVal.Channel.includes('Name')) {
item.dataarr.push({ 'MobileNo': curVal.mobnum})
}
})
return obj1;
}, [])
};
But when obj2 is empty I get this error :
(node:10837) UnhandledPromiseRejectionWarning: TypeError: obj2.reduce is not a function
at func (/home/user/Desktop/serv.js:708:37)
at breakdata (/home/user/Desktop/serv.js:720:5)
at cached.getMulti.then (/home/user/Desktop/serv.js:643:7)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:10837) 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:10837) [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.
Ignore these line from the error above :
at breakdata (/home/user/Desktop/serv.js:720:5)
at cached.getMulti.then (/home/user/Desktop/serv.js:643:7)\
as they are thrown because obj2.reduce doesn't give any output when the exception is thrown.
How do I handle : obj2.reduce is not a function when obj2 array is empty? I don't want this code to throw exceptions as the log file generated is huge.
I'm not getting how to add a catch block here. How do I do this?
Related
currently I'm struggling with fingerprint in my previous project i solved this in this way:
const test = async (req, res, next) => {
// other code
const FingerprintJS = require('#fingerprintjs/fingerprintjs');
const store = require('store')
FingerprintJS.get({
preprocessor: function(key, value) {
return value
}
},function(components){
let values = components.map(function (component) { return component.value });
let device_id = FingerprintJS.x64hash128(values.join(''), 31);
store.set('print', { device: device_id })
});
await new Promise(resolve => setTimeout(resolve, 1000));
// other code
};
But now I cant set it up to work.. I'm getting error in console.log :
(node:4940) UnhandledPromiseRejectionWarning: TypeError: FingerprintJS.get is not a function
at login (C:\Users\PC06\Desktop\project\backend\controllers\clients-controllers.js:53:17)
(node:4940) 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:4940) [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 help for this?
I am using the ipfs-http-client module.
This is my script
async function main() {
const ipfs_client = require('ipfs-http-client');
const client = ipfs_client({recursive: false});
async function addFile(file_data) {
const cid = function (data) {
return client.add(data).then(cid =>{return cid;}).catch(err=>{
console.log(err)})
}
const real_cid = cid(file_data).then(result=>{return result}).catch(err=>{console.log(err)});
return real_cid;
}
const sendFileToNet = async (file) => {
return await addFile(file);
}
async function getFile(cid){
//error occurs here
for await (const chunk of client.cat(cid)) {
console.info(chunk)
}
return content;
}
const getFileFromNet = async()=>{
return await getFile();
}
getFileFromNet("QmU77sHBUuCT12324e9Re59bNHekpKg1PdCpiVAj3MFLiH").then(r => console.log(r));
module.exports = {sendFileToNet, getFileFromNet
};
}
main();
(node:22889) UnhandledPromiseRejectionWarning: Error: Invalid version, must be a number equal to 1 or 0
at Function.validateCID (/home/chipego/Documents/MedChain/node_modules/ipfs-http-client/node_modules/cids/src/index.js:346:13)
at new CID (/home/chipego/Documents/MedChain/node_modules/ipfs-http-client/node_modules/cids/src/index.js:174:9)
at Object.cat (/home/chipego/Documents/MedChain/node_modules/ipfs-http-client/src/cat.js:16:48)
at cat.next ()
at getFile (/home/chipego/Documents/MedChain/logic/ipfs_submit_controller.js:23:26)
at getFileFromNet (/home/chipego/Documents/MedChain/logic/ipfs_submit_controller.js:30:22)
at main (/home/chipego/Documents/MedChain/logic/ipfs_submit_controller.js:32:5)
at Object. (/home/chipego/Documents/MedChain/logic/ipfs_submit_controller.js:39:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
(Use node --trace-warnings ... to show where the warning was created)
(node:22889) 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: 2)
(node:22889) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with
Your getFile function takes an argument. You are invoking it in getFileFromNet but not passing the argument in.
I have an application where I continuously have to run some async code in the background. I created a minimal simulation of my application.
let promise_chain = Promise.resolve();
let rejected_promise_count = 0;
const interval_id = setInterval(
// Do some important polling. I will just always reject to demonstrate the problem.
() => {
promise_chain = promise_chain.then(() => {
rejected_promise_count += 1;
return Promise.reject();
})
},
10
);
// Set timeout simulates the program being done.
setTimeout(
() => {
clearInterval(interval_id);
promise_chain
.then(() => end("Resolved! :D"))
.catch(() => end("Rejected! D:"));
},
1000
);
function end(message) {
console.log(message);
console.log(`Amount of rejected promises created: `, rejected_promise_count);
}
This gives a long list of these:
(node:29217) UnhandledPromiseRejectionWarning: undefined
(node:29217) 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)
(node:29217) [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.
(node:29217) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 2)
(node:29217) UnhandledPromiseRejectionWarning: undefined
(node:29217) 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: 3)
(node:29217) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 3)
(node:29217) UnhandledPromiseRejectionWarning: undefined
(node:29217) 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: 4)
(node:29217) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 4)
Eventually ended by these:
(node:29217) UnhandledPromiseRejectionWarning: undefined
(node:29217) 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: 87)
(node:29217) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 87)
(node:29217) UnhandledPromiseRejectionWarning: undefined
(node:29217) 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: 88)
Rejected! D:
Amount of rejected promises created: 1
(node:30920) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 89)
I'm not quite sure why node doesn't want me to handle these asynchronously, but given it runs on an interval, I really have no other choice.
How do I get rid of the endless list of warnings, and more importantly, how do I make sure in the future node will not terminate this process because it thinks I am not handling the rejections?
It depends what you want to do, the correct way to handle it is like this:
const interval_id = setInterval(
() => {
promise_chain = promise_chain.then(() => {
rejected_promise_count += 1;
return Promise.reject();
});
//ignore error here, you catch it in the setTimeout
promise_chain.catch(ignore=>ignore);
},
10
);
That will output:
Rejected! D:
Amount of rejected promises created: 1
This because you reject the first time so the chain is broken and all other then are not executed.
If you would like to continue executing and want to know how many passed and failed you can do something like this:
//using actual results
let results = [];
//special Fail value to indicate rejected promise
let Fail = function(reason){this.reason=reason;};
let isFail = object=>(object&&object.constructor===Fail);
let isNotFail = object=>!isFail(object);
let promise_chain;
let somePromise = ()=>Promise.reject(new Error("Some reason"));
const interval_id = setInterval(
() => {
promise_chain = (promise_chain||somePromise())
.then(
result => {
results.push(result);
return somePromise();
}
)
.catch(//catch the rejection and return a Fail type value
error=>new Fail(error)
);
},
10
);
// Set timeout simulates the program being done.
setTimeout(
() => {
clearInterval(interval_id);
promise_chain
.then(
result => {
//add the last result to results
results.push(result);
console.log(
"rejected promises:",
results.filter(isFail).length
//you can get the errors like so:
//results.filter(isFail).map(fail=>fail.reason)
);
console.log(
"resolved promises:",
results.filter(isNotFail).length
//results.filter(isNotFail) is an array of resolved values
)
}
);
//this will never reject because we catch rejected promises
// and add fail types to results
// .catch(() => end("Rejected! D:"));
},
1000
);
I have written to following db query to get back all posts with a certain offset:
async function getPaginationPosts(start, size) {
try {
const posts = await knex("posts").select().where({
deleted: false,
}).orderBy("createdAt").limit(size).offset(start)
} catch (e) {
console.log(e.message)
console.log(e.stack)
}
return posts
}
However, I am getting the following Unhandled Promise Rejection
(node:1824) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: posts is n
ot defined
(node:1824) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejection
s that are not handled will terminate the Node.js process with a non-zero exit code.
My problem is that I do not get any further information about the error in the console.
Any suggestions from your site:
How to debug these types of rejections properly?
What is wrong with the above code?
Thank you in advance for your replies!
Update
I changed my function to the following:
async function getPaginationPosts(size, offset) {
try {
return await knex("posts").select().where({
deleted: false,
}).orderBy("createdAt").limit(size).offset(offset)
} catch (e) {
console.log(e.message)
console.log(e.stack)
return null
}
}
Now I am getting the following exception:
(node:9096) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: start is n
ot defined
I do not use a variable start in my function.
Any suggestions what I am doing wrong here?
A convenient way to log unhandled rejections - is to add listener (usually at entry point of your app, i.e. main.js) that looks like this
process.on("unhandledRejection", (error) => {
console.error(error); // This prints error with stack included (as for normal errors)
throw error; // Following best practices re-throw error and let the process exit with error code
});
posts are defined not in the correct place. Define them outside of try/catch block or return result from try block:
async function getPaginationPosts(start, size) {
try {
return await knex("posts").select().where({
deleted: false,
}).orderBy("createdAt").limit(size).offset(start)
} catch (e) {
console.log(e.message)
console.log(e.stack)
return null
}
}
Or:
async function getPaginationPosts(start, size) {
let posts
try {
posts = await knex("posts").select().where({
deleted: false,
}).orderBy("createdAt").limit(size).offset(start)
} catch (e) {
console.log(e.message)
console.log(e.stack)
}
return posts
}
I have a promise function called findProperty which in this case rejects like this:
reject('ERR: Unknown propertyID or inactive property in call of newBooking');
And this is my handler that calls findProperty:
async function main() {
var res = "";
try {
findProperty();
res = await findUser(userEmail);
res = await findUser(agentEmail);
res = await getUsers();
}
catch(err) {
console.error(err);
console.log(" newBooking: " + err);
callback( { error:true, err } );
}
}
main();
This causes the following error:
(node:10276) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ERR: Unknown propertyID or inactive property in call of newBooking
(node:10276) [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.
I dont get this, I got my catch(err) shouldn't that be enough?
Just tried something, this works fine:
resolve('ERR: Unknown propertyID or inactive property in call of newBooking');
But this gives the error:
reject('ERR: Unknown propertyID or inactive property in call of newBooking');
If findProperty returns a promise, you need to await it in order to trigger the failure within the context of the async function; otherwise the rejection disappears into outer space.
To "fire and forget" without waiting, yet catch failures with your try/catch:
findProperty().catch(e => { throw e; });