React JS Unexpected reserved word 'await' [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am struggling with this async await issue I have created async function and for that I am calling await but I am getting error Unexpected reserved word 'await'
Below is the async function
export const addProductCall = async (product) => {
let accessToken = window.localStorage.getItem("accessToken");
await axios.post(SERVER_URI + '/inventoryservice/v1/item',
product,
{ headers: { "Authorization": "Bearer " + accessToken, "Content-Type": "application/json" } })
}
Below is the function from where I am calling this function.
const handleSubmit = () => {
const data = {
'storeId': customerDetails.id, category, categoryToBeAdded, description,
productCode, productName, sku, price, unit, quantity
}
await addProductCall(data);
}

You cannot use the await keyword outside of an async function :
const handleSubmit = () => {
const data = {
'storeId': customerDetails.id, category, categoryToBeAdded, description,
productCode, productName, sku, price, unit, quantity
}
await addProductCall(data);
}
should be :
const handleSubmit = async () => {
const data = {
'storeId': customerDetails.id, category, categoryToBeAdded, description,
productCode, productName, sku, price, unit, quantity
}
await addProductCall(data);
}

Replace
const handleSubmit = () => {
with
const handleSubmit = async () => {
For await to work, it needs to be wrapped inside an async function

Related

Is and how memory is cleaned in cron tasks

The question is pretty self-explanatory but I wanna know how to deal with scheduled tasks whether it is cron, setTimeout, setInterval etc. Let's say I have multiple variables initialized inside it. If the task keeps repeating is it gonna keep filling memory or will it clean itself after some time? This might sound simple but I'm a beginner. I will throw my code here where I send one API request to check the value of one variable and another one to increase it by one. I can probably safely take some of the variables outside just fine but the question remains the same.
const { GraphQLClient, gql } = require ('graphql-request')
const Cron = require ('croner')
const job = Cron('0 14 * * *', () => {
async function main() {
console.log("start")
const endpoint = 'https://graphql.anilist.co/'
const graphQLClient = new GraphQLClient(endpoint, {
headers: {
authorization: 'Token hidden for obvious reasons.',
},
})
const query_check = gql`
mutation ($mediaId: Int, $status: MediaListStatus) {
SaveMediaListEntry (mediaId: $mediaId, status: $status) {
id
status
progress
}
}
`
const variables = {
mediaId: "1337"
}
const check = await graphQLClient.request(query_check,variables)
console.log(`przed ${check.SaveMediaListEntry.progress}`)
const query_new = gql`
mutation ($mediaId: Int, $status: MediaListStatus, $progress: Int) {
SaveMediaListEntry (mediaId: $mediaId, status: $status, progress: $progress) {
id
status
progress
}
}
`
const new_variables = {
mediaId: `1337`,
progress: `${check.SaveMediaListEntry.progress + 1}`
}
const new_query = await graphQLClient.request(query_new,new_variables)
console.log(`po ${new_query.SaveMediaListEntry.progress}`)
}
main().catch((error) => console.error(error))
});

The settimeout is returning all values of the object, why is it not returning only one value? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
The community is reviewing whether to reopen this question as of 6 months ago.
Improve this question
const RequestStatus = () => {
const status = 'SUCCESS'
const object = {
SUCCESS: console.log('Success'),
PROGRESS: console.log('Progress'),
ERROR: console.log('Errror'),
}
useEffect(() => {
setTimeout(() => {
return object[status]
}, 5000)
}, [status])
}
You see all three statuses logged because you are calling all console.log when you create your object
Here are two ways you can modify your code to fix this
In the first method (which is the one I recommend) I am mapping the messages to the status codes and getting the approprite message using object[status]
const RequestStatus = () => {
const status = 'SUCCESS'
const object = {
SUCCESS: 'Success',
PROGRESS: 'Progress',
ERROR: 'Errror',
}
useEffect(() => {
setTimeout(() => {
console.log(object[status]);
}, 5000)
}, [status])
}
In the second one I create lambda functions for each status code that define what happens when that status code occurs
const RequestStatus = () => {
const status = 'SUCCESS'
const object = {
SUCCESS: ()=>{console.log('Success')},
PROGRESS: ()=>{console.log('Progress')},
ERROR: ()=>{console.log('Errror')},
}
useEffect(() => {
setTimeout(() => {
object[status]();
}, 5000)
}, [status])
}

Unable to solve this Express.js/ JavaScript programming issue [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
try {
console.log('11111')
const {
data: { tasks },
} = await axios.get('/api/v1/tasks')
console.log('22222 ' + await axios.get('/api/v1/tasks') )
console.log('33333 ' + tasks)
Issue is: tasks is undefined
The problem was in Backend..
the route associated with await axios.get('/api/v1/tasks') i.e get('/api/v1/tasks') had this code
``` const getAllTasks = async (req,res) => {
try{
const tasks = await Task.find({})
res.status(200).json(tasks)
}
catch(error){
res.status(500).send({msg: error})
}
}```
instead above. It should be
```const getAllTasks = async (req,res) => {
try{
const tasks = await Task.find({})
res.status(200).json({ tasks })
}
catch(error){
res.status(500).send({msg: error})
}
}```
The change is in res.status(200).json({ tasks })

URl works in postman returns full news array but returns empty in javascript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
In postman when i use the url below the news property on the response in full with articles
https://api.currentsapi.services/v1/search?country=us&language=en&apiKey="..."
But in javascript I'm getting an empty news array.
Here is the javascript:
function displayNewsResults(responseJson){
console.log(responseJson)
}
let newsBaseUrl = 'https://api.currentsapi.services/v1/search'
let newsApiKey = '...';
function getNews(country) {
let params = {
country: country,
language: 'us',
apiKey: newsApiKey
}
let queryString = formatQueryParams(params);
let url = newsBaseUrl + '?' + queryString;
console.log(url)
let req = new Request(url);
fetch(req)
.then(response => {
if (response.ok) {
return response.json();
}
else {
throw new Error(response.statusText);
}
})
.then(responseJson => displayNewsResults(responseJson))
.catch(err => {
$('#js-error-message-news').empty().text(`Something went wrong: ${err.message}`).show();
})
}
The function displayNewsResults returns:
{status: "ok", news: Array(0), page: 1}
The code seems correct and the result is also correct, the mistake however is that in your code you're calling the API with the language parameter set to us instead of en

What is the difference between find and findOne in this case? Why it does not work? [duplicate]

This question already has answers here:
find() and findOne() methods in MongoDB showing different results
(6 answers)
Closed 3 years ago.
I have this sort of code. When I search find()... It does not work while searching with findOne()... is working.
Thanks for your answer!
const task = await Task.find({_id, owner: req.user._id}) //This does not work
const task = await Task.findOne({_id, owner: req.user._id}) // This works
router.patch('/tasks/:id', auth, async (req, res) => {
const updates = Object.keys(req.body) // The opposite is Object.values()
const _id = req.params.id
const allowedUpdates = ['description', 'completed']
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send({error: 'Invalid update!'})
}
try {
const task = await Task.findOne({_id, owner: req.user._id})
if (!task) {
return res.status(404).send()
}
updates.forEach((update) => task[update] = req.body[update])
await task.save()
res.send(task)
} catch (e) {
res.status(500).send(e)
}
})
at first, you should use the same syntax to show an error when it coming it the no result may be because the condition isenter image description here not an achievement.

Categories

Resources