UnhandledPromiseRejectionWarning, readfile, writefile, async - javascript

my code is not working and i get the following error:
TypeError: inventors.push is not a function
at file:///C:/Users/tomma/OneDrive/Bureaublad/taller%20de%20programacion%202/javascriptFiles/TP2-2C-c/async/ejercicioPromesas.js:10:19
(node:9536) UnhandledPromiseRejectionWarning: ReferenceError: inventors is not defined
at file:///C:/Users/tomma/OneDrive/Bureaublad/taller%20de%20programacion%202/javascriptFiles/TP2-2C-c/async/ejercicioPromesas.js:15:46
(Use `node --trace-warnings ...` to show where the warning was created)
(node:9536) 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:9536) [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.
code:
import fs from 'fs/promises'
const path = './inventors.json';
const inventor = {first: 'Rene', last: ' Favarolo', year: 1923};
fs.readFile(path, 'utf-8').then(data =>{
const inventors = JSON.parse(data);
console.log(inventors);
await inventors.push(inventor);
return fs.writeFile (path,JSON.stringify(inventors, null, ' '))
}).then( () => (
console.log('Archivo actualizado')
)
);
Please help me

Please use the Try Catch statement.
import fs from 'fs/promises' const path = './inventors.json';
const inventor = {first: 'Rene', last: ' Favarolo', year: 1923};
fs.readFile(path, 'utf-8').then(async(data) =>{
try{
const inventors = JSON.parse(data);
console.log(inventors);
await inventors.push(inventor);
}
catch(err){
}
}
return fs.writeFile (path,JSON.stringify(inventors, null, ' '))
}).then( () => ( console.log('Archivo actualizado') ) );

Related

UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function (NodeJS- Sequelize)

I'm following a tutorial on NodeJs on youtube, but when it comes to deleting users by id, it doesn't work like what's on the tutorial. But on that video everything seems to work perfectly. This is my code. Where am I wrong? Looking forward to everyone's comments.
let deleteUserByID = (userId)=>{
return new Promise(async(resolve, reject)=>{
try{
let user = await db.User.findOne({
where: {id: userId}
})
if(user){
await user.destroy();
}
resolve();
}catch(e){
reject(e);
}
})
}
And this is the error displayed on the terminal screen:
(node:11140) UnhandledPromiseRejectionWarning: TypeError: user.destroy is not a function
at...
at...
at...
...
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11140) 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:11140) [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.
After a while of searching on the internet, i found the solution, everything is working and seems to be fine, anyone can refer to it if they have the same error as mine.
Upvote if it works for you
let deleteUserByID=(userId)=> {
return db.User.destroy({ where: { id: userId } })
.then(rows => Promise.resolve(rows === 1))
}
Or another solution:
let deleteUserByID = (userId) => {
return new Promise(async (resolve, reject) => {
await db.User.findOne({
where: {
id: userId
}
})
await db.User.destroy({
where: {
id: userId
}
})
resolve({
errCode: 0,
message: `The user is deleted`
})
})
}

UnhandledPromiseRejectionWarning: Error: This contract object doesn't have address set yet, please set an address first

I was going through the flashloan course and I was having trouble with section 13 Pull Kyber Prices.
I am getting this error
(node:43614) UnhandledPromiseRejectionWarning: Error: This contract object doesn't have address set yet, please set an address first
Here is my full code:
require('dotenv').config();
const Web3 = require('web3');
const abis = require('./abis');
const { mainnet: addresses } = require('./addresses');
const web3 = new Web3(
new Web3.providers.WebsocketProvider(process.env.INFURA_URL)
);
const kyber = new web3.eth.Contract(
abis.kyber.kyberNetworkProxy,
addresses.kyber.kyberNetworProxy
);
const AMOUNT_ETH = 100;
const RECENT_ETH_PRICE = 2400;
const AMOUNT_ETH_WEI = web3.utils.toWei(AMOUNT_ETH.toString());
const AMOUNT_DAI_WEI = web3.utils.toWei((AMOUNT_ETH * RECENT_ETH_PRICE).toString());
web3.eth.subscribe('newBlockHeaders')
.on('data', async block => {
console.log('New Block Recieved # ' + block.number);
const kyberResult = await Promise.all([
kyber
.methods
.getExpectedRate(
addresses.tokens.dai,
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
AMOUNT_DAI_WEI
)
.call(),
kyber
.methods
.getExpectedRate(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
addresses.tokens.dai,
AMOUNT_ETH_WEI
)
.call()
]);
console.log(kyberResults);
})
.on('error', error => {
console.log(error);
});
The error that I am getting is this:
(node:43614) UnhandledPromiseRejectionWarning: Error: This contract object doesn't have address set yet, please set an address first.
at Object.ContractNoAddressDefinedError (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-core-helpers/lib/errors.js:122:16)
at Object._processExecuteArguments (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-eth-contract/lib/index.js:728:22)
at Object._executeMethod (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-eth-contract/lib/index.js:744:68)
at Subscription.<anonymous> (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/run-arbitrage.js:34:18)
at Subscription.emit (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/eventemitter3/index.js:181:35)
at /Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-core-subscriptions/lib/subscription.js:242:35
at Array.forEach (<anonymous>)
at Object.callback (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-core-subscriptions/lib/subscription.js:234:28)
at WebsocketProvider.data (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-core-requestmanager/lib/index.js:99:73)
at WebsocketProvider.emit (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/eventemitter3/index.js:181:35)
at /Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-providers-ws/lib/index.js:104:19
at Array.forEach (<anonymous>)
at WebsocketProvider._onMessage (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/web3-providers-ws/lib/index.js:102:69)
at W3CWebSocket._dispatchEvent [as dispatchEvent] (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/yaeti/lib/EventTarget.js:115:12)
at W3CWebSocket.onMessage (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/websocket/lib/W3CWebSocket.js:234:14)
at WebSocketConnection.<anonymous> (/Users/wealthywhyte/Desktop/Solidity/profitable-flashloanz/node_modules/websocket/lib/W3CWebSocket.js:205:19)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:43614) 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:43614) [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 believe that the problem is lines 31 and 38 after the method ".getExpectedRate" I am just not sure what to switch those addresses that he provided out with.

When I run a script it tells me that filter is not a function. [Discord.js]

I have a script where you need to answer to the bot with yes (da in the script) or no (nu in the script) and when I run the script on discord it tells me that filter is not a function. I have to mention that I am a beginner.
The script is this:
module.exports = {
name: 'moneda',
description: 'mai usor de luat o decizie',
execute(message, args){
let decizii = [
"Fata",
"Spate",
]
let decizie = decizii[Math.floor(Math.random() * (decizii.length))]
message.reply(`Ti-a picat ${decizie}`);
let decizii1 = [
"Fata",
"Spate",
]
let decizie1 = decizii1[Math.floor(Math.random() * (decizii1.length))]
message.channel.send('Mai vrei sa incerci odata?').then(async (start) => {
message.channel.awaitMessage(filter, { maxMatches: 1, time: 60000, errors: ['time']}).then(async (collected) => {
if(collected.first().content === 'da') {message.channel.send(decizie1)} else if (collected.first().content === 'nu') {return}
})
})
}
}
The error is this:
(node:8340) UnhandledPromiseRejectionWarning: ReferenceError: filter is not defined
at C:\Users\ADRIAN\Desktop\ZerOne BOT\commands\moneda.js:18:42
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8340) 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:8340) [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.
filter is not defined, means that you have to create a filter.
This is an example filter, for your problem:
let filter = m => m.author.id === message.author.id;

UnhandledPromiseRejectionWarning when using .reduce

const sendData = (response, language, locale) => {
try {
console.log(response.reduce((prev, curr) => prev + curr.confirmed, 0));
} catch (error) {
console.error('error');
}
};
and my fetch function:
const fetchGeneralData = async (param) => {
try {
let res = await axios.get(
`https://localhost/api/${param}`,
);
msg.reply(sendData(res.data.results), language, momentLocale);
} catch (error) {
msg.reply(language.errorMessage);
console.error(error, 'Error on fetchGeneralData');
}
};
The console.log shows me the correct value but for some reason, I still getting the errors.
I have tried adding async/await inside sendData but it did not work. My fetchGeneralData func works fine when i'm trying to return the date without modify it.
Here is the full message:
(node:5500) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: t.match is not a function
(node:5500) 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:5500) [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.

Cannot resolve error unhandled promise rejection and NoSuchSessionError

I am trying to build some code but I get those two errors:
(node:12909) UnhandledPromiseRejectionWarning: NoSuchSessionError: Tried to run command without establishing a connection
at Object.throwDecodedError (/home/matthew/node_modules/selenium-webdriver/lib/error.js:550:15)
at parseHttpResponse (/home/matthew/node_modules/selenium-webdriver/lib/http.js:563:13)
at Executor.execute (/home/matthew/node_modules/selenium-webdriver/lib/http.js:489:26)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:12909) 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:12909) [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:12909) UnhandledPromiseRejectionWarning: NoSuchSessionError: Tried to run command without establishing a connection
at Object.throwDecodedError (/home/matthew/node_modules/selenium-webdriver/lib/error.js:550:15)
at parseHttpResponse (/home/matthew/node_modules/selenium-webdriver/lib/http.js:563:13)
at Executor.execute (/home/matthew/node_modules/selenium-webdriver/lib/http.js:489:26)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:12909) 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)
function review_balance() {
if (balance_amount > 0) {
console.log("This address has " + balance_amount + "Bitcoin");
}
else {
console.log("0 Bitcoins!");
}
}
async function searching() {
console.log("Waiting for address to be scanned on the Bitcoin blockchain...");
const result = await review_balance();
console.log(result);
}
searching();
driver.close();
This is the part of the program that is the most important and contains the problem. Can anyone give me any advice? I would be really thankful.
Solution using Promise:
let check_balance = new Promise((resolve, reject) => {
driver.get("https://explorer.bitcoin.com/btc/address/" + address);
let balance_amount = driver.findElement(webdriver.By.className("amount")).getText();
if (balance_amount > 0) {
resolve('This wallet has ' + balance_amount + ' Bitcoins.');
}
else {
reject('0 Bitcoins!');
}})check_balance.then((message) => {
console.log(message);}).catch((message) => {
console.log(message);}) setTimeout(function () {
driver.quit();}, 8000);

Categories

Resources