Extract response data array from fetch function with post method - javascript

I've written an async function which is able to get a response from an API I've written in Python but I can't get the data into an array which I can then use to update my frontend application.
The code is as follows:
async function postData(URL) {
let rawResponse = await fetch(URL, {
method: "Post",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(inputData),
});
const data = await rawResponse.json();
console.log(data);
return data;
}
let response1 = postData();
console.log(response1);
let response2 = postData()["returnedData"];
console.log(response2);
The code returns the array I want when I console.log the data variable within the function. However, it returns an array called 'Promise{pending}'* for response1 which contains the desired data but I am not able to manipulate it and returns 'undefined' for response2. What am I doing wrong?
Thanks in advance!
*pending even though the PromiseState is 'fulfilled'

PostData Function is a aync Function so returns a Promise so you must use await before calling it or .then
async function postData(URL) {
let rawResponse = await fetch(URL, {
method: "Post",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(inputData),
});
const data = await rawResponse.json();
console.log(data);
return data;
}
// Method 1
const init = async () => {
let response1 = await postData();
console.log(response1);
let response2 = await postData()["returnedData"];
console.log(response2);
}
init();
// Method 2
(async () => {
let response1 = await postData();
console.log(response1);
let response2 = await postData()["returnedData"];
console.log(response2);
})()

Related

How to return the fetch from an async call [duplicate]

This question already has answers here:
async/await always returns promise
(4 answers)
Closed 2 months ago.
I'm really confused about asynchronous functions in general, but I can't seem to return what the api has fetched. Using console.log() gives all the results but I need the function's path (array) for later use.
function callRelation(id) {
(async () => {
const api = await fetch(
"https://www.overpass-api.de/api/interpreter?",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: "[out:json];rel(" + id + ");(._;>;);out;",
},
);
const request = await api.json();
let path = [];
for (let pair of request.elements){
if (pair.type === "node"){
path.push([pair.lat, pair.lon]);
}
}
console.log(path)
return path;
})();
}
let test = callRelation(10000);
console.log(test);
I've tried using something called a callback, but I failed miserably at that.
You await to get return from promise function.
async function callRelation(id) {
const api = await fetch("https://www.overpass-api.de/api/interpreter?", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: "[out:json];rel(" + id + ");(._;>;);out;",
});
const request = await api.json();
let path = [];
for (let pair of request.elements) {
if (pair.type === "node") {
path.push([pair.lat, pair.lon]);
}
}
console.log(path);
return path;
}
(async function () {
let test = await callRelation(10000);
console.log(test);
})();

Resolve an Await function if it takes more than x seconds in Javascript / Node.js

I have an await function() which waits for an external API. Usually, these APIs take 600ms to return data. But sometimes it's taking around 10 seconds. So how do I write a function so that if it takes more than 1 second, then break that function and resolve anyway (don’t wait for the API)
Here's the main function code which calls the API.
console.log("Before Await");
await fetchExternalAPI("data");
console.log("Continue if success or takes more than x seconds");
The actual function:
const fetch = require('node-fetch');
module.exports = async function fetchExternalAPI(data) {
try {
const response = await fetch("https://www.example.com/api/log", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
const returnData = await response.json();
console.log("Response: " + JSON.stringify(returnData))
return returnData
}
catch (e) {
console.log("Error: " + e)
return e
}
}
I want to return success fo the above function
if fetch is success
or if exceeded more than x seconds
Both should return success no matter the real output.
You can use AbortController to abort the fetch method, inside a setTimeout with 1sec, and if the fetch resolved before the setTimeout callback execute, then clearTimeout
const fetch = require('node-fetch');
module.exports = async function fetchExternalAPI(data) {
try {
let controller = new AbortController();
let timeId = setTimeout(() => {
controller.abort()
}, 1000)
const response = await fetch("https://www.example.com/api/log", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
signal: controller.signal
});
clearTimeout(timeId)
const returnData = await response.json();
console.log("Response: " + JSON.stringify(returnData))
return returnData
}
catch (e) {
console.log("Error: " + e)
return e
}
}
I think you need to use Axios.
npm i axios
than in body you have one property timeout.
const instance = await axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
You can add a promise in your call to resolve on time and reject if too long.
The following code has not been tested but that's the idea
const fetch = require('node-fetch');
module.exports = async function fetchExternalAPI(data) {
try {
const response = await fetch("https://www.example.com/api/log", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
await new Promise((resolve, reject) => {
setTimeout(reject, 50000));
resolve();
}).then(() => {
const returnData = await response.json();
console.log("Response: " + JSON.stringify(returnData))
return returnData
}).catch(() => {
return 'Took too long';
}));
}
catch (e) {
console.log("Error: " + e)
return e
}
}

javascript undefined value using fetch in function

If I call this function:
async function delete_get_note() {
let query = {
'command': 'delete_get_content',
'note_id': input_note_id.value
}
let response = await fetch(
'../api/api.php',
{
method: 'POST',
headers: {'Content-Type': 'application/json;charset=utf-8'},
body: JSON.stringify(query)
}
);
let result = await response.json();
log.innerHTML = result.log;
}
log displays the content of the json returned by my server. However, if I try to encapsulate the call to fetch in a function:
async function json_exchange(object) {
let response = await fetch(
'../api/api.php',
{
method: 'POST',
headers: {'Content-Type': 'application/json;charset=utf-8'},
body: JSON.stringify(object)
});
return await response.json;
}
And call:
async function delete_get_note() {
let query = {
'command': 'delete_get_content',
'note_id': input_note_id.value
}
let result = await json_exchange(query);
log.innerHTML = result.log;
}
Then log displays undefined.
What did I get wrong when I tried to put the call to fetch in a function ?
You forgot to add the parentheses to the json call:
return await response.json;
-->
return await response.json()
Tip: You can use TypeScript checking to easily detect such errors:

Vue - returning the result of a synchronous method

I'm struggling to return the synchronous results of the method below.
I call the method from a different method:
var result = this.getVendor(id)
console.log(result)
Here is the fetch method:
methods: {
async getData(id) {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
.then(res => res.json())
.then(data => {
return data;
});
await response;
}
}
How do I return the results response of the getData() function to show in the console?
Async functions Always return a promise.
You can use the await syntax to return it properly.
async getData(id) {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
const data = await response.json()
return data
}
You can access the data out of that function anywhere you call it.
let data = null
object.getData(2)
.then(x => {
data = x
})
Also if you are going to use async await make sure to use try and catch to handle any errors that come up.
async getData(id) {
try {
const response = await fetch(`${API_URL}api/${id}`, {
method: "GET",
headers: {
authorization: `Bearer ${localStorage.token}`
}
})
const data = await response.json()
return data
}
} catch(err) {
console.error(err)
}

Can't get data from fetch

I'm trying to make a fetch call and it works but when I try to get the result from another function I always get undefined.
This is my code:
const fetch_output = async (data) => {
await fetch("execute_command", {
method: "POST",
credentials: "same-origin",
headers: {
"X-CSRFToken": getCookie("csrftoken"),
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(function(response) {
return response.json()
}).then(function(response) {
console.log(response)
//I get the correct response here
return response
}).catch(function(ex) {
console.log("Ha habido algún error: ", ex)
})
}
const write_outputs = async () => {
for (const platform_id of platforms_ids) {
const data = {
platform_id:platform_id,
command:command
}
await fetch_output(data).then((resp)=>{
console.log(resp)
//I get undefined
})
}
}
write_outputs()
I've tried everything but I just don't know what am i doing wrong.
it is because an async function returns a promise that resolves to the returned value from the function
(async () => {})().then(value => console.log("value = ", value)); // undefined
(async () => {return 1})().then(value => console.log("value =" , value)); // 1
as you are not returning anything from fetch_output, it resolves to undefined
You should return from the fetch_output function instead of using await.
Also, because fetch is already a promise you can use a normal function instead of an async one
Because you call await fetch_output() you should not use .then() to retrieve its result. Drop the await.
Why? await replaces function().then().catch() with result = await function() in the way it handles a Promise or an async function. Use await or .then() but not both.

Categories

Resources