This question already has answers here:
await is only valid in async function
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
In a file called getData.js , I wrote the following code
module.exports = async function (page, id) {
const options = {
...
};
axios
.request(options)
.then((response) => {
myData = JSON.stringify(response.data);
return myData;
})
.catch((error) => {
console.error(error);
});
};
Now in my main index.js file, I imported the above module then I have this snippet,
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
let finalData = await getData(myPage, myID);
res.end(finalData);
});
When I run this node crashes and I get this error
SyntaxError: await is only valid in async functions and the top level bodies of modules
How do I make my code to work? I thought of using async-await becuase response.data is very big, but clearly I don't understand async-await functions fully. In the external module, If I try to return myData outside the .then block and also don't use async-await, then I get undefined finalData.
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 months ago.
I'm trying to perform an axios get request.
axios
.get("http://10.10.0.145/api/session", {
headers: {
'Cookie' : user_cookie
}
},
)
.then(res => {
result = res.data;
id_user_intervention = res.data.id;
console.log(id_user_intervention); //IS NOT UNDEFINED
})
.catch(error => {
console.error(error)
})
console.log(id_user_intervention); //IS UNDEFINED
I need to use id_user_intervention outside the axios request. I assign res.data.id to id_user_intervention, but this variable is undefined outside the axios request...how can I solve this problem?
First of all, it's better you learn async/await on javascript. Then, try the following solution:-
const testFunction = async () => {
let id_user_intervention = null;
try {
const response = await axios.get("http://10.10.0.145/api/session", {
headers: {
'Cookie': user_cookie
}
})
id_user_intervention = response.data.id;
} catch (err) {
console.error(err);
}
return id_user_intervention;
}
const anotherFunction = async () => {
const data = await testFunction();
console.log(data);
}
Hope it will work properly.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
How do I ensure a promise has resolved in my configuration file. For example my configuration looks like the below.
const fetch = require("node-fetch");
const fetchToken = async () => {
return await fetch('www.token-endpoint.com', {
method: "POST",
headers: {
ContentType: "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
secret: "this is a secret",
})
})
}
const ACCESS_TOKEN = fetchToken()
.then((res) => { return res.json() })
.then(...)
// And so on
// Now I want my promise to definitely resolve
module.exports = {
accessToken: ACCESS_TOKEN // This will be undefined unless my promise has resolved
}
After this I would like to use the token.
const config = require("./config")
// Use config.accessToken knowing it is well defined.
you can do something like this ,node fetch actually has
a built in function for converting the response to JSON, but it does not do it automatically in the same way that Axios and SuperAgent do. recent versions of this library use promises, so we're able to use async/await syntax with it as well:
const fetch = require('node-fetch');
(async () => {
try {
const response = await fetch('www.token-endpoint.com')
const json = await response.json()
console.log(json.url);
console.log(json.explanation);
} catch (error) {
console.log(error.response.body);
}
})();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm working on two functions about my project. First function is async function:
async function abc(params) {
(...)
var sdata = JSON.stringify(params);
fetch(...)
.then(response => response.json())
.then(data => {
/*do something*/
})
.catch(err => {
/*err do something*/
})
}
Second function is:
function xyz (param){
irrevelantFunction(param);
}
I tried to execute this two functions like below:
abc(params).then(xyz(param));
but it doesn't work. How can I solve this problem? Many thanks for your precious support.
If you are using async then you can avoid .then, kindly see the sample snippet code
async function abc(params) {
var sdata = JSON.stringify(params);
try{
const response = await fetch(...)
if(response.ok){
const body = await response.json();
xyz(body)
return
}
const cusotomError = {
message: 'something went wrong'
}
throw customError
}catch(error){
console.log(error) // you can show error to ui logic
}
function xyz (param){
irrevelantFunction(param);
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am writing a class in JavaScript that sends HTTP requests for a specific URL. I'm trying to test that class with Mocha but for some reason, the method fetchUrl() returns undefined. I can't seem to figure out why. I literally started writing in JavaScript a day ago, therefore I am still trying to learn and adjust to it.
fetchUrl () {
var request = require('request')
var res
request(this.url, function (error, response, body) {
console.log('error:', error) // Print the error if one occurred
if (response.statusCode !== 200) {
console.log('received status code other than 200 OK')
this.error = true
}
res = response
console.log('statusCode:', response && response.statusCode) // Print the response status code if a response was received
// console.log('body:', body) // Print the HTML for the requested url.
this.html = body
})
return res
}
describe('Test Http request to google.com', function () {
it('should return 200', function (done) {
assert.equal(httpCon.fetchUrl().statusCode, 200)
done()
})
})
You should use Nock libray to mocking HTTP request.
const axios = require('axios');
module.exports = {
getUser(username) {
return axios
.get(`https://api.github.com/users/${username}`)
.then(res => res.data)
.catch(error => console.log(error));
}
};
And here test case:
describe('Get User tests', () => {
beforeEach(() => {
nock('https://api.github.com')
.get('/users/octocat')
.reply(200, response);
});
});
For more details, you can look at this: mocking-http also look into this answer of SO. source
I think you should only return res inside the callback, otherwise it will return undefined since the program keeps running...
https://developer.mozilla.org/en-US/docs/Glossary/Callback_function
You may want to take a look on callback funcionality
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm trying to create a function which returns a JSON object from an URL.
It should work like this:
function getObject(url) {
// return undefined when the url or json is invalid
return object;
}
So that I can use it in this way, if I would use the following URL:
var object = getObject('http://ip.jsontest.com/');
console.log('My IP is: ' + object.ip)
The JSON from the example looks like this:
{"ip": "127.0.0.1"}
So the code above should log this:
My IP is: 127.0.0.1
I already tried it with the request module and found this example on StackOverflow:
request.get({
url: 'http://ip.jsontest.com/',
json: true,
headers: {'User-Agent': 'request'} }, (err, res, data) => {
if (err) {
console.log('Error:', err)
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode)
} else {
// data is already parsed as JSON:
console.log(data)
}
})
The data is displayed in the console as it should, but I found no way to use the it like in the example I provided above.
Is there a way to solve this without callbacks? I read that requests are asynchronous, but I need a synchronus solution.
No there is no way to do this synchronously. You could look into using the fetch api and an async function if they're supported in your environment.
For example:
async function getMyIpAndDoSomething() {
const response = await fetch("http://ip.jsontest.com/");
const object = await response.json();
console.log(object.ip);
}