I am trying to make a Node.js bot, so I found a module, installed it and tried out its example code.
Now, I have an async function that loads some text from an API. This is the code:
(async () => {
// Display user's balance
balance = kraken.api('Balance');
console.log(await balance);
})();
When I run the code above, this is what I get in commandprompt:
{
error: [],
result: { A: '2.0', BC: '0.005', BCA: '111' }
}
How would I be able to make it only log a specific part of this, which looks like an array?
I've tried doing stuff like (to get it to return 2.0):
console.log(await balance.result.A)
But that does not seem to work as it returns this:
(node:6604) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'A' of undefined
(node:6604) [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.
Out of ideas and need help.. Thanks!
You habe to put your await statement in parentheses, like this:
console.log((await balance).result.A);
This will fetch the balance asynchronously, then log the result property.
Related
I am not knowledgeable in NodeJS or JS so bare that in mind. I have been playing around with a radix trie module Merkle-Patricia-Tree and it's taken me down a rabbit hole when using a level module similar to Google's leveldb to store the radix trie in persistent storage.
what I think I know:
The Merkle-Patricia-Tree module requires a levelup dependency which wraps level down as the first parameter when instantiating a new trie
Seems to write to the store with trie.put(key,value), but having problems reading with trie.get(key)
In one of the error files in Markle-Patricia-Trie library...
constructor(leveldb) {
this._leveldb = leveldb !== null && leveldb !== void 0 ? leveldb : level();
}
does pass in the levelup(leveldown('path')) when instantiating trie with db but somehow says that here in the same file (included affected files)...
async get(key) {
let value = null;
try {
value = await this._leveldb.get(key, exports.ENCODING_OPTS);
}
catch (error) {
if (error.notFound) {
// not found, returning null
}
else {
throw error;
}
}
return value;
}
this...
(node:17128) UnhandledPromiseRejectionWarning: TypeError: this._leveldb.get is not a function
at CheckpointDB.get (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\db.js:27:41)
at CheckpointDB.get (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\checkpointDb.js:85:35)
at SecureTrie.lookupNode (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\baseTrie.js:250:31)
at SecureTrie._lookupNode (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\baseTrie.js:266:21)
at \cryptoNetwork\node_modules\merkle-patricia-tree\dist\util\walkController.js:41:40
at new Promise (<anonymous>)
at WalkController.startWalk (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\util\walkController.js:36:22)
at Function.newWalk (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\util\walkController.js:32:24)
at SecureTrie.walkTrie (\cryptoNetwork\node_modules\merkle-patricia-tree\dist\baseTrie.js:221:47)
at \cryptoNetwork\node_modules\merkle-patricia-tree\dist\baseTrie.js:200:28
(node:17128) 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:17128) [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.
The encoding is dealt with properly so assume under that axiom
aggregator code:
testing()
{
programData.volatile.modularVariables.action = 'read';
programData.volatile.modularVariables.user = 'blahblahblahblah';
programData.volatile.modularVariables.createTrie();
};
object with relevant code (I'm aware of extra unneeded code, editing time of writing this)
//assume object containing these functions/variables inside
user: '-', //aggregator initializes this and action
action: '-',
createTrie: ()=>{switch(programData.volatile.modularVariables.action){case 'read':programData.volatile.modularVariables.read(programData.persistent.paths.srcRoot,programData.volatile.modularVariables.encoding.utf8,programData.volatile.modularVariables.handleTrie);break;case 'write':programData.volatile.modularVariables.read(programData.persistent.paths.srcRoot,programData.volatile.modularVariables.encoding.utf8,programData.volatile.modularVariables.handleTrie);break;case 'new':programData.volatile.modularVariables.newTrie(db);break;default: console.log(`%c${programData.volatile.debug.debugStrings.errCodes.createTrie}: Error with action selection`,'color: red');}},
handleTrie: async (err,data)=>{var userBIN = Buffer.from(programData.volatile.modularVariables.user); var root=Buffer.from(data,programData.volatile.modularVariables.encoding.hex);console.log(root); switch(programData.volatile.modularVariables.action){case 'read': const trie = new merkle_patricia_tree_1.SecureTrie(programData.persistent.paths.srcRoot,root);
var result = await trie.get(userBIN); console.log(result)}},
read: (file,encoding,cb)=>{fs.readFile(file,encoding,cb)},
encoding: {utf8:'utf8',hex:'hex',base64:'base64',BIN:(data,encoding)=>{Buffer.from(data,encoding)}}, //Depricate BIN asap,
srcRoot: './vortex/root.txt',
conclusion
I am stumped, I am not sure what I am doing wrong or what is wrong with Markle-Patricia-Trie (or the leveldb). My questions are, what am I doing wrong? Can you explain to me what's wrong?. Thank you :).
In the handleTrie arrow function I used as callback for the read arrow function, I passed in the path of the store, not the level instance itself...
Every time a message is sent in a specific channel, I want to print it to the console (with console.log). I am also going to color it with npm install colors. I go everywhere, even on Stack Overflow, but I cannot seem to find any information. I am coding a Scholastic Bowl-helping bot. Below is the code I have tried (I found this on Stack Overflow.)
message.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
(Note that when I say 'channel-id' I mean the actual ID of the channel.)
The error I am getting is that message.first is not a thing.
How do I fix this error, and how can I get the most recent message in discord.js?
Edit: The exact error I got is this:
(node:12352) UnhandledPromiseRejectionWarning: TypeError: messages.first is not a function
at C:\Users\[user redacted]\Desktop\SchoBot\index.js:57:32
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:12352) 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:12352) [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.
Below is the edit for the 3rd comment on this question (sorted by oldest):
message.channel.fetch({ limit: 1 }).then(messages => {
let lastMessage = message.channel.first();
if (message.channel.lastMessage = 'channel-id'){
console.log(lastMessage.red);
}
})
Use message.channel.messages.fetch() instead of message.channel.fetch().
I didn't find the message.first function in the discord.js documentation, so I am not sure if it works. But you don't really need that function to fetch a message. The fetch function already did that for you.
In your case, the option limit: 1 will only return the most recent message, which is the command you use to trigger the fetch. If you want to fetch the most recent message but not your command, you should use limit: 2 instead and remove your command in the object later.
The fetch function will return an object containing message id and the content.
I assume that message.fetch needs to be message.channel.fetch
Hello in my nodejs api i need fetch data inside the loop and then again need to do a loop and save a data in another table how should i achive that?
Here is some snippet that i have tried but not succeeded for the same
async myAPIname(){
let _this = this;
try {
const bets = await Bet.find({gameId:ObjectId(request.matchId)}).lean()
bets.map(async (bet) => {
let Users = await Users.findOne({_id:ObjectId(element.userId)}).lean();
Users.parentTree.map(async (user) => {
console.log(user);
// also over here based on the some calculation need to save the data in another table
})
})
} catch (error) {
_this.res.send({ status: 0, message: error });
}
}
Also in above snipped tried with foreach loop as well but not succeeded
and error from above spinet like this:
(node:30886) UnhandledPromiseRejectionWarning: ReferenceError: Cannot access 'Users' before initialization
at /var/www/html/api/app/controllers/SomeController.js:228:30
at Array.map (<anonymous>)
at SomeController.myAPIname (/var/www/html/api/app/controllers/SomeController.js:227:18)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) 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:30886) [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:30886) UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
at /var/www/html/api/app/controllers/SomeController.js:220:27
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:30886) 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)
Any Help will really appreciated
I can see two problems:
firstly the await inside a map call doesn't work like you think. It will work fine in a for-of loop but not in a map, foreach etc.
https://zellwk.com/blog/async-await-in-loops/ has a good an explanation as anywhere.
Secondly where you are calling let Users = Users.findOne, the compiler thinks that Users on the left hand side of the assignment is the same as the Users on the right hand side so it complains that when its calling Users.findOne, Users isn't initialised.
to use asynchronous handling with Array.prototype.map() you have to wrap it with Promise.all() and wait for it to fulfill.
!! however notice that iterations are executed in asynchronous way, not waiting for previous iteration to settle.
const sleep = async (time = 3000) => new Promise(resolve => setTimeout(resolve, time));
(async () => {
const array = [1,3,4,2];
console.log('start', array);
const mapped =await Promise.all(array.map(async e => {
await sleep(e * 1000);
console.log(e);
return `done for ${e}`;
}));
console.log('end', mapped);
})();
So a discord bot I'm creating has a twitch notifications, and it uses snekfetch to create a looping request function. On the return of the function I have client.channels.get(id).send(embed) however it doesn't message the channel id which I've given it.
const api = `https://api.twitch.tv/helix/streams?user_login=${streamer}`;
snekfetch.get(api).set('Client-ID', "XXXXXXXXXXXXXX").then(r => {
if (r.body.stream === null) {
setInterval(() => {
snekfetch.get(api).then(console.log(r.body))
}, 30000);
} else {
const embed = new discord.RichEmbed()
.setAuthor(
`${r.body.data.user_name} is live on Twitch`,
)
.setThumbnail(`http://static-cdn.jtvnw.net/ttv-boxart/live_user_${streamer}-500x500.jpg`)
.addField('Views', `${r.body.data.viewer_count}`, true)
return bot.channels.get(XXXXXXXXXXXX).send("TEST");
}
});
I have named my client bot so instead of client.channels it's bot.channels
It should in theory send the TEST message to whatever channel id I give it, however instead I get an error.
(node:62565) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
at /Users/XXXXXXX/Desktop/HelperBot/main.js:61:50
at processTicksAndRejections (internal/process/task_queues.js:89:5)
(node:62565) 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:62565) [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.
your error has to do with that not all channels are text channels. Before you can send a message it has to be sure it can. so you could check if that's the case with the function .isText() when you have checked that it is the type should change to text channels which are dm text and news at this moment. those have the .send function
The error said it can't find the .send("Test") function of something that is not defined.
So the error come from bot.channels.get(XXXX)
bot.channels return a collection. If you search a specific item of this collection. You need to use .find and not .get
More info about .find here : https://discord.js.org/#/docs/main/stable/class/Collection?scrollTo=find
Below is my code. Test-case is getting passed whether my actual is equal to expected or not equal.It is just showing warning message when it is not equal but my test-case is shown in green .I cant see any failure message in report.
Code:
this.VerifyAccountHolder=async function(){
var testPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(elementAccount.isPresent());
}, 200);
});
var result = await testPromise;
assert.equal(result,true,"wrong result");
Warning message:
(node:8784) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): AssertionError: expected false to equal
true (node:8784) [DEP0018] DeprecationWarning: Unhandled promise
rejections are deprecated. In the future, promise rejections that are
not handled will terminate the Nodejs process with a non-zero exit
code.
how to avoid this warning
I want to display the assertion error in report.I'm new to JavaScript protractor framework.
You could simplify this whole function by removing the promise entirely. I'm really not sure why you need setTimeout either. The element is going to present or it isn't. You could probably use ExpectedConditions.presenceOf() with browser.wait() but this seems redundant to me. As much as I hate to suggest this, if you REALLY must wait for 200ms before checking the element is present just use browser.sleep(). I would use this as a last resort though. Try getting it to work without any explicit waits if you can.
this.VerifyAccountHolder = function() {
browser.sleep(200); //only use this if you REALLY need it
return elementAccount.isPresent();
});
And then you should move the assertion to a test instead of keeping it in this function.
it('should be present', async () => {
let result = await pageObjectName.VerifyAccountHolder();
expect(result).toEqual(true);
//or if you prefer to keep using a node assertion instead
//assert.equal(result,true,"element not present");
});