Async line of code is like its invinsible - discord.js

I dont know much of javaScript and i wanted to make a bot from a youtube tutorial. Now the video said to type this:
(async () => {
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
}
} catch (err) {
if (err) console.error(err);
}
})
Inside the client.once("ready",
So it turned out something like this:
client.once("ready", () => {
console.log("Bot is online.");
const CLIENT_ID = client.user.id;
const rest = new REST({
version: "9"
}).setToken(process.env.TOKEN);
(async () => {
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
}
} catch (err) {
if (err) console.error(err);
}
})
});
Now as you can see it says that if it finds client id it should type on console "Locally" to see if it works. But the terminal is like it ignores the whole async it just says that the bot is online nothing for the commands. What did i do wrong

Instead of defining a separate asynchronous function inside the ready handler function, why not just make the ready handler function itself asynchronous? Here's an example:
client.once("ready", async () => {
console.log("Bot is online.");
const CLIENT_ID = client.user.id;
const rest = new REST({
version: "9"
}).setToken(process.env.TOKEN);
try {
if (process.env.ENV === "production") {
await rest.put(Routes.applicationCommands(CLIENT_ID), {
body: commands
});
console.log("Globally");
} else {
await rest.put(Routes.applicationGuildCommands(CLIENT_ID, process.env.GUILD_ID)
, {
body: commands
});
console.log("Locally");
}
} catch (err) {
if (err) console.error(err);
}
});
That should allow the async function to run.
EDIT
Your if statements were slightly incorrect. You are checking if process.env.ENV equals production, and else, you are once again checking if it equals production. I've fixed that in this answer.

Related

Nock not mocking GET request

I'm trying to follow run a cypress test with next.js and nock. Based on other examples and following the video, I tried to mock a simple GET request. However, my test fails on the cy.request as it makes an actual call instead of the mock call.
index.js
const nock = require('nock');
const http = require('http');
const next = require('next');
const injectDevServer = require('#cypress/react/plugins/next');
// start the Next.js server when Cypress starts
module.exports = async (on, config) => {
if (process.env.CUSTOM_SERVER == 'false') {
injectDevServer(on, config);
} else {
await startCustomServer(on, config);
}
return config;
};
async function startCustomServer(on, config) {
config.supportFile = false;
const app = next({ dev: true });
const handleNextRequests = app.getRequestHandler();
await app.prepare();
const customServer = new http.Server(async (req, res) => {
return handleNextRequests(req, res);
});
await new Promise((resolve, reject) => {
customServer.listen(3000, (err) => {
if (err) {
return reject(err);
}
console.log('> Ready on http://localhost:3000');
resolve();
});
});
// register handlers for cy.task command
on('task', {
clearNock() {
nock.restore();
nock.cleanAll();
return null;
},
async nock({ hostname, method, path, statusCode, body }) {
nock.activate();
console.log(
'nock will: %s %s%s respond with %d %o',
method,
hostname,
path,
statusCode,
body
);
// add one-time network stub like
method = method.toLowerCase();
nock(hostname)[method](path).reply(statusCode, body);
return null;
},
});
}
my-test.spec.js
describe('my-test', () => {
beforeEach(() => {
cy.task('clearNock');
})
it('execute', () => {
cy.task('nock', {
hostname: 'https://localhost:3000',
method: 'GET',
path: '/myapi/api/layout',
statusCode: 200,
body: {
id: 'NmbFtH69hFd',
status: 200,
success: true
}
})
cy.request(
'https://localhost:3000/myapi/api/layout/'
).as('API'); // <-- Fails here with error
cy.get('API').then((response) => {
assert.exists(response.success);
});
});
});

How to make a PATCH request in ReactJS ? (with Nestjs)

nestjs controller.ts
#Patch(':id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
#Body('shippingAddr') addrShipping: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling, addrShipping);
return null;
}
nestjs service.ts
async updateProduct(
addressId: string,
addrBilling: boolean,
addrShipping: boolean,
) {
const updatedProduct = await this.findAddress(addressId);
if (addrBilling) {
updatedProduct.billingAddr = addrBilling;
}
if (addrShipping) {
updatedProduct.shippingAddr = addrShipping;
}
updatedProduct.save();
}
there is no problem here. I can patch in localhost:8000/address/addressid in postman and change billingAddr to true or false.the backend is working properly.
how can i call react with axios?
page.js
const ChangeBillingAddress = async (param,param2) => {
try {
await authService.setBilling(param,param2).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
return....
<Button size='sm' variant={data.billingAddr === true ? ("outline-secondary") : ("info")} onClick={() => ChangeBillingAddress (data._id,data.billingAddr)}>
auth.service.js
const setBilling = async (param,param2) => {
let adressid = `${param}`;
const url = `http://localhost:8001/address/`+ adressid ;
return axios.patch(url,param, param2).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}
I have to make sure the parameters are the billlingddress field and change it to true.
I can't make any changes when react button click
Since patch method is working fine in postman, and server is also working fine, here's a tip for frontend debugging
Hard code url id and replace param with hard coded values too:
const setBilling = async (param,param2) => {
// let adressid = `${param}`;
const url = `http://localhost:8001/address/123`; // hard code a addressid
return axios.patch(url,param, param2).then((response) => { // hard code params too
console.log(response); // see console result
if (response.data.token) {
// localStorage.setItem("user", JSON.stringify(response.data));
}
// return response.data;
})
}
now it worked correctly
#Patch('/:id')
async updateProduct(
#Param('id') addrId: string,
#Body('billingAddr') addrBilling: boolean,
) {
await this.addrService.updateProduct(addrId, addrBilling);
return null;
}
const ChangeBillingAddress = async (param) => {
try {
await authService.setBilling(param,true).then(
() => {
window.location.reload();
},
(error) => {
console.log(error);
}
);
}
catch (err) {
console.log(err);
}
}
const setBilling= async (param,param2) => {
let id = `${param}`;
const url = `http://localhost:8001/address/`+ id;
return axios.patch(url,{billingAddr: param2}).then((response) => {
if (response.data.token) {
localStorage.setItem("user", JSON.stringify(response.data));
}
return response.data;
})
}

Update a specific variable at config.json using a command

So I am trying to create a command that allows a user to enter on or off duty. I am planning to create a panel later displaying who is on or off duty. But I am having trouble updating the value of in the config.json file which corresponds to the staff ID
I am checking the users ID and if it already exists in the config.json file the bot won't write down the ID again
const { Util } = require('discord.js');
const fs = require('fs');
const path = require('path');
module.exports = {
config:{
name:'test'
},
run: async(bot, message, args) => {
const staffMemberID = message.member.id;
function jsonRead(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf-8', (err, content) => {
if (err) {
reject(err);
} else {
try {
resolve(JSON.parse(content));
} catch (err) {
reject(err);
}
}
});
});
}
function jsonWrite(filePath, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, JSON.stringify(data), (err) => {
if (err) {
reject(err);
}
resolve(true);
});
});
}
const filePath = path.resolve(`${__dirname}/../storage/config.json`);
if(bot.config.status.find(u => staffMemberID)) {
try {
const config = await jsonRead(filePath);
config.status.push({
value:'On Duty',
});
jsonWrite(filePath, config);
message.channel.send(`Success. ${config.status}`);
} catch (err) {
console.log(err);
}
} else {
try {
const config = await jsonRead(filePath);
config.status.push({
name:staffMember,
value:'On Duty',
});
jsonWrite(filePath, config);
message.channel.send(`Success. ${config.status}`);
} catch (err) {
console.log(err);
}
}
}
}

Clearing an item from AsyncStorage - React native

I'm new to react native currently i'm working on a project that needs to update a specific value in async storage. I tried by clearing an item from Asyncstorage using this code await AsyncStorage.removeItem(key); but when i used it console throws an error like this 'await' is only allowed within async functions . But i'm using an async function
const getExceedCountData = async () => {
const token = await AsyncStorage.getItem("#userToken")
const exceedcount = await AsyncStorage.getItem("#exceedCount")
if(!exceedcount){
try {
setLoading(true)
axios
.get(constants.BASE_URL + "getexceedcount?token=" +token)
.then(response => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
}
catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})
.catch(error => {
console.log(error);
});
} catch(error) {
console.log(error);
}
}else{
setExceedCount({ value:exceedcount, error: '' })
}
}
I don't know why this issue occured. Any help is appreciable.
You need to notate the function as async.
.then(async (response) => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
}
catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})
The scope of the function inside .then is not declared as async. This should fix your problem:
.then(async response => {
if(response.data.status == 1){
try {
await AsyncStorage.removeItem("#exceedCount");
} catch(exception) {
console.log('Error Occured');
}
AsyncStorage.setItem("#exceedCount", response.data.result);
setExceedCount({ value:response.data.result, error: '' })
}
})

Axios promise will never resolve

For the life of me, I can never get my Axios.post promise to resolve.
I know that my front end and backend are perfectly connected.
Try/catch blocks to return the resolved promise haven't worked either.
No matter what I do, I can never get inside of my promise.then() function. What am I doing incorrectly in my backend file?
CODE THAT HASN'T WORKED TO RESOLVE THE PROMISE
async handleDateSubmit() {
let resolvedPromise = await Axios.post(
"http://localhost:3001/get_number_of_dates_from_email",
{
email: this.state.user_email_m
}
);
resolvedPromise
.then(response => {
//I can never get to here.
console.log("Made it inside");
})
.catch(err => console.log(err));
}
//---attempt two----//
async getResolvedPromise() {
try {
return await Axios.post(
"http://localhost:3001/get_number_of_dates_from_email",
{
email: this.state.user_email_m
}
);
} catch (error) {
console.log(error);
}
}
async handleDateSubmit() {
let resolvedPromise = this.getResolvedPromise();
//work with resolvedPromsie
}
CURRENT CODE
//------------send_info.js front end file----------//
handleDateSubmit() {
Axios.post('http://localhost:3001/get_number_of_dates_from_email', {
email: this.state.user_email_m
})
.then((response) => {
//I can never get to here.
console.log("Made it inside");
})
.catch(err => console.log(err));
}
//---------------server.js backend file---------------//
router.route('/get_number_of_dates_from_email').post(function (req, res) {
//"user_email" is correct in my schema model and "req.body.email" is always what it should be
User.findOne({ user_email: req.body.email }, (err, foundUser) => {
console.log("Inside of findOne()");
if (err) {
return res.send(err);
}
else {
let numDates = foundUser.dates_list.length;
//I always get here and numDates is always correct
console.log("Number of dates: ", numDates);
return res.json({ "numDates": numDates }); //Should I be using res.send()?
}
});
});
It seems like you're confusing promises and resolved promises at times in your code
// Attempt one
async handleDateSubmit() {
try {
let resolvedPromise = await Axios.post(
"http://localhost:3001/get_number_of_dates_from_email",
{
email: this.state.user_email_m
}
);
// Here resolvedPromise as stated by its name is not a promise anymore, thus you can't use .then()
// You can directly work with resolvedPromise as it contains the response.
} catch (e) {
console.error(e)
}
}
// Attempt two
async getResolvedPromise() {
try {
// Here you're returning the resolved promise, but the async await syntax turn your function into an AsyncFunction object
// This type of function will wrap the return value in a promise if it's not one
return await Axios.post(
"http://localhost:3001/get_number_of_dates_from_email",
{
email: this.state.user_email_m
}
);
} catch (error) {
console.log(error);
}
}
async handleDateSubmit() {
// Thus you need to await the result of your function
let resolvedPromise = await this.getResolvedPromise();
}

Resources