How do I nest callbacks for async functions in javascript? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I've looked but haven't been able to find a solution to this specific problem, so I thought I'd ask. I'm a novice javascript developer who clearly needs to read more about scope, callbacks and promises.
I'm trying to nest callbacks to get data out of a http request using the fetch API in javascript. At this point in my project, I've sent data to a node back end, called a few apis, then sent json data back to the client.
I now want to access that data outside of the function getServerData in the below.
I've tried a few different things but haven't been able to figure it out. I feel like I'm missing something obvious.
My current code is below:
//I want to access callback data here
const getServerData = userData => {
// declare data to send
const apiData = userData;
// declare route
const url = 'http://localhost:3030/nodeserver';
// declare POST request options
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(apiData)
};
// Async function to fetch from Node server w/ callback
const fetchUIData = async callback => {
await fetch(url, options)
.then(response => response.json())
.then(data => {
callback(data);
})
.catch(err =>
console.log(
`There was an error fetching from the API POST route:${err}`
)
);
};
// Variable to store callback data
let serverData = [];
// Callback function to use data from fetch
return fetchUIData(data => {
serverData = data;
console.log(serverData);
});
};

You don't nest callbacks when using await. The whole point of await is to get rid of the .then( .then( .then())) callback hell and nesting. Either use .then() (if you enjoy callback hells :) or await; not both together, it doesn't make sense.
const getServerData = async userData => {
const url = 'http://localhost:3030/nodeserver';
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(userData)
};
const response = await fetch(url, options);
return response.json()
};
const serverData = await getServerData(userData);
console.log(serverData); // <-- Tadaaa

As soon as the result is based on some asynchronous work, you need to return it using a Promise or a callback.
So const getServerData = userData => { has to either accept a callback, or to return a Promise.
The callback in that part of your code does not seem to have any purpose:
return fetchUIData(data => {
serverData = data;
console.log(serverData);
});
It seems as if you just want to return data from getServerData
So also that part does not make any sense:
.then(data => {
callback(data);
})
So the code could look like this:
const getServerData = userData => {
// declare data to send
const apiData = userData;
// declare route
const url = 'http://localhost:3030/nodeserver';
// declare POST request options
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(apiData)
};
// Async function to fetch from Node server w/ callback
const fetchUIData = () => {
return fetch(url, options)
.then(response => response.json())
.catch(err =>
console.log(
`There was an error fetching from the API POST route:${err}`
)
return null;
);
};
// Callback function to use data from fetch
return fetchUIData()
};
But even that could be simplified:
const getServerData = async userData => {
// declare data to send
const apiData = userData;
// declare route
const url = 'http://localhost:3030/nodeserver';
// declare POST request options
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(apiData)
};
// fetch from Node server
try {
let response = await fetch(url, options)
return response.json()
} catch( err ) {
console.log(
`There was an error fetching from the API POST route:${err}`
)
return null;
}
};
The whole try-catch block is probably also something you want to remove, letting the error propagate. In the current form, the getServerData will always fulfill and only log the error. That's in many cases not what you want. But that depends on the exact use case.
The function is then used that way:
let data = await getServerData();

Related

Promise all with axios in react native app

I'm making a react-native weather forecast app. And I'm trying to get all the data using 2 promise all methods
This is the function I call in useEffect
async function getData(){
try{
Promise.all(_.map(savedPlaces, getCurrentWeather)).then((response) => {console.log("current", response.data)})
Promise.all(_.map(savedPlaces, getDailyWeather)).then((response) => {console.log("daily", response.data)})
}
catch(error){
console.log(error)
}
}
The savedPlaces variable is an array with names of the cities I want to get the weather for
And this is one of the two fuctions i use to get the data
const getCurrentWeather = async (places) =>{
const options = {
method: 'GET',
url: 'https://community-open-weather-map.p.rapidapi.com/weather',
params: {q: places.name, lang: 'null', units: 'metric', mode: JSON},
headers: {
'x-rapidapi-host': 'community-open-weather-map.p.rapidapi.com',
'x-rapidapi-key': 'xxx'
}
};
const request = await axios.request(options).then(response => {console.log(response.data)})
return request
}
The other funtion is basicaly the same except little changes in options
And the issu is that I can see the data in print out in this code fragment
.then(response => {console.log(response.data)})
inside the getCurrentWeather functions but when I try to print them out in .then after Promise.all I get undefined, same with the other function.
current [undefined, undefined]
And I'm asking how to properly do it
Here:
const request = await axios.request(options)
.then(response => {console.log(response.data)})
The callback under then prints the data in the console, but has no return statement (returns undefined). Therefore this
return request
returns undefined wrapped in a promise.
Add return response (or return response.data) after the console.log and it should get better.

How to perform multiple axios POST requests in a For Loop with different body data for each iteration of loop?

I have an array of postData whose each element is the body that needs to be passed in every time we make an Axios POST request.
I am facing unhandled promise rejection error when running the script, i am fairly new to asynchronous programming and have been struggling with this error.
The script goes like this:
const axios = require('axios')
const fs = require('fs')
var textFileContainingData = fs.readFileSync('data.txt').toString().split("\r\n");
console.log(textFileContainingData);
let axiosConfig = {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer XXXXXX',
'X-Correlation-ID': '1234',
}
};
for (i=0; i<textFileContainingData.length; i++) {
var postData = {
data: textFileContainingData[i]
};
console.log(postData)
const getData = async () => {
try {
return await axios.post('https://example-api-url/endpoint', postData, axiosConfig)
} catch (error) {
console.error(error)
}
}
const callEndpoint = async () => {
const responseData = await getData()
console.log(responseData)
}
callEndpoint();
}
My first answer was mistaken, I've removed it.
The error is related to a promise, probably axios.post is failing, post your stacktrace after trying your code
Some additional notes:
Use .forEach for readability
use axios.post({}).then(response => {}).catch(err => {}), you may omit .then and leave only .catch()

How do i pass result of callback into variable and access the var freely

I know there's a ton of question similar to my question, but i didn't see any good case to help me,
I have a callback from native function bridge and this how i used it on JS:
getAllParameter((data)=>{
console.log(data) // data is Javascript Object
})
I've tried this to get the value of data:
getAllParameter((data)=>{
return new Promise((resolve)=> resolve(showToken(data.Token)))
})
async function showToken(token){
var res = await token
return res
}
var isiToken = showToken()
console.log("isiToken")
console.log(isiToken)
but the result is:
isiToken
{ _40: 0, _65: 0, _55: null, _72: null }
i don't know whats wrong with my code, i want to get the value of data outside of the getAllParameter, how can i do that properly?
the reason why i need to get the result of getAllParameter and used it freely is because I've token value inside the data, and i need to use the token in axios instance config
so the full code of my file should be:
getAllParameter((data)=>{
return new Promise((resolve)=> resolve(showToken(data.Token)))
})
async function showToken(token){
var res = await token
console.log("res")
console.log(res)
return res
}
var isiToken = showToken()
console.log("isiToken")
console.log(isiToken)
const http = Axios.create ({
baseURL: Constants.APILink,
timeout: Constants.Timeout,
headers: {'Content-Type': 'application/json', 'Authorization': 'bearer '+isiToken}
export default http
});
I am not sure of your getAllParameter definition but that method should be calling your callback at the end. Hoping that it does that, here is snippet that does what you want
(function() {
var data;
function getAllParam(callback) {
console.log("getAllParam");
callback("getAllParam");
}
getAllParam((data)=> {
this.data = data);
console.log(this.data);
});
})();
So, what I am doing is
Creating a variable called data;
Assigning the callback response to my data variable. (Read closures & this in arrow functions)
Use that later.
But here is the limitation with my code: This doesn't work when getAllParam is an async function. Meaning if the callback is not called in sequence. You have to use promises then.
EDIT
app.js
function getAllParam(callback) {
console.log("getAllParam");
callback({Token: "getAllParam"});
}
var httpPromise = new Promise(resolve => {
getAllParam((data) => {
let token = data.Token;
console.log("Creating http from here using token");
let http = Axios.create({ bearer: token});
resolve(http);
})
});
export default httpPromise;
file_that_imports_app_js.js
import httpPromise from "./app.js";
async function init() {
let http = await httpPromise;
http.get("/", ...)
}
init();

Function does not wait for fetch request

I am trying to retrieve JSON from a server as an initial state.
But it looks like the function doesn't wait for the response.
I looked at different Stackoverflow posts like How to return return from a promise callback with fetch? but the answers I found didn't seem to help.
// Get the best initial state available
// 1. Check for local storage
// 2. Use hardcoded state with the test value from the server.
export function getInitialState() {
if (localStorage.getItem('Backup') != undefined) {
return returnValue = Map(JSON.parse(localStorage.getItem('Backup')))
} else {
var returnValue = initialState
const GetJSON = (url) => {
let myHeaders = new Headers();
let options = {
method: 'GET',
headers: myHeaders,
mode: 'cors'
};
return fetch(url, options).then(response => response.json());
};
GetJSON('https://example.com/api/v1/endpoint/valid/').then(result => {
// Console.log gives a good result
console.log(result)
// The return is undefined
return returnValue.setIn(['test'], result)
});
}
}
In this case, I receive an undefined while I expect a returnValue JSON where the test property is updated from the server.
So I really want the function getInitialState() to return the state. And to do this it needs to wait for the fetch to finish. I also tried to place return before the GetJSON but this had no effect.
Oke, so I just tried the following:
GetJSON('https://example.com/api/v1/endpoint/valid/').then(result => {
console.log('aaa')
console.log(result)
localstorage.setItem('init', result)
console.log('bbb')
}).then(result => {
console.log('done')
});
This returns aaa and result.
But the localStorage is never set, and the bbb and done are never shown.

Return fetch .json inside object.

I have an API calling function that I would like to return the response.json() content as well as the response.status together in a single object.
Like so:
const getData = data => {
return fetch('/api_endpoint',{
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
.then(response => {
return {
body: response.json(),
status: response.status
}
})
}
The trouble is that response.json() is a promise, so I can't pull it's value until it's resolved.
I can hack around it by doing this:
const getData = data => {
let statusRes = undefined;
return fetch('/api_endpoint',{
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
.then(response => {
statusRes = response.status;
return response.json()
})
.then(data => {
return {
body: data,
status: statusRes
}
}
)
}
But it just feels WRONG. Anybody have a better idea?
const getData = data => {
return fetch('/api_endpoint',{
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
.then(async response => {
return {
body: await response.json(),
status: response.status
}
})
}
es6
async/await
might help it look more clean
There is no need for the variable if it bothers you, you can return tuples (array in ES).
In this case variable is save enough since it's used only once and within the same promise stack.
const getData = data => {
return fetch('/api_endpoint',{
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
.then(response =>
//promise all can receive non promise values
Promise.all([//resolve to a "tuple"
response.status,
response.json()
])
)
.then(
/**use deconstruct**/([status,body]) =>
//object literal syntax is confused with
// function body if not wrapped in parentheses
({
body,
status
})
)
}
Or do as Joseph suggested:
const getData = data => {
return fetch('/api_endpoint',{
method: 'GET',
headers: {
'Content-type': 'application/json'
}
})
.then(response =>
response.json()
.then(
body=>({
body,
status:response.status
})
)
)
}
update
Here I would like to explain why using await can lead to functions that do too much. If your function looks ugly and solve it with await then likely your function was doing too much to begin with and you didn't solve the underlying problem.
Imagine your json data has dates but dates in json are strings, you'd like to make a request and return a body/status object but the body needs to have real dates.
An example of this can be demonstrated with the following:
typeof JSON.parse(JSON.stringify({startDate:new Date()})).startDate//is string
You could say you need a function that goes:
from URL to promise of response
from promise of response to promise of object
from promise of object to promise of object with actual dates
from response and promise of object with actual dates to promise of body/status.
Say url is type a and promise of response is type b and so on and so on. Then you need the following:
a -> b -> c -> d ; [b,d]-> e
Instead of writing one function that goes a -> e it's better to write 4 functions:
a -> b
b -> c
c -> d
[b,d] -> e
You can pipe output from 1 into 2 and from 2 into 3 with promise chain 1.then(2).then(3) The problem is that function 2 gets a response that you don't use until function 4.
This is a common problem with composing functions to do something like a -> e because c -> d (setting actual dates) does not care about response but [b,d] -> e does.
A solution to this common problem can be threading results of functions (I'm not sure of the official name for this in functional programming, please let me know if you know). In a functional style program you have types (a,b,c,d,e) and functions that go from type a to b, or b to c ... For a to c we can compose a to b and b to c. But we also have a function that will go from tuple [b,d] to e
If you look at the 4th function objectAndResponseToObjectAndStatusObject it takes a tuple of response (output of 1st function) and object with dates (output of 3rd function) using a utility called thread created with createThread.
//this goes into a library of utility functions
const promiseLike = val =>
(val&&typeof val.then === "function");
const REPLACE = {};
const SAVE = {}
const createThread = (saved=[]) => (fn,action) => arg =>{
const processResult = result =>{
const addAndReturn = result => {
(action===SAVE)?saved = saved.concat([result]):false;
(action===REPLACE)?saved = [result]:false;
return result;
};
return (promiseLike(result))
? result.then(addAndReturn)
: addAndReturn(result)
}
return (promiseLike(arg))
? arg.then(
result=>
fn(saved.concat([result]))
)
.then(processResult)
: processResult(fn(saved.concat([arg])))
};
const jsonWithActualDates = keyIsDate => object => {
const recur = object =>
Object.assign(
{},
object,
Object.keys(object).reduce(
(o,key)=>{
(object[key]&&(typeof object[key] === "object"))
? o[key] = recur(object[key])
: (keyIsDate(key))
? o[key] = new Date(object[key])
: o[key] = object[key];
return o;
},
{}
)
);
return recur(object);
}
const testJSON = JSON.stringify({
startDate:new Date(),
other:"some other value",
range:{
min:new Date(Date.now()-100000),
max:new Date(Date.now()+100000),
other:22
}
});
//library of application specific implementation (type a to b)
const urlToResponse = url => //a -> b
Promise.resolve({
status:200,
json:()=>JSON.parse(testJSON)
});
const responseToObject = response => response.json();//b -> c
const objectWithDates = object =>//c -> d
jsonWithActualDates
(x=>x.toLowerCase().indexOf("date")!==-1||x==="min"||x==="max")
(object);
const objectAndResponseToObjectAndStatusObject = ([response,object]) =>//d -> e
({
body:object,
status:response.status
});
//actual work flow
const getData = (url) => {
const thread = createThread();
return Promise.resolve(url)
.then( thread(urlToResponse,SAVE) )//save the response
.then( responseToObject )//does not use threaded value
.then( objectWithDates )//does no use threaded value
.then( thread(objectAndResponseToObjectAndStatusObject) )//uses threaded value
};
getData("some url")
.then(
results=>console.log(results)
);
The async await syntax of getData would look like this:
const getData = async (url) => {
const response = await urlToResponse(url);
const data = await responseToObject(response);
const dataWithDates = objectWithDates(data);
return objectAndResponseToObjectAndStatusObject([response,dataWithDates]);
};
You could ask yourself is getData not doing too much? No, getData is not actually implementing anything, it's composing functions that have the implementation to convert url to response, response to data ... GetData is only composing functions with the implementations.
Why not use closure
You could write the non async syntax of getData having the response value available in closure like so:
const getData = (url) =>
urlToResponse(url).then(
response=>
responseToObject(response)
.then(objectWithDates)
.then(o=>objectAndResponseToObjectAndStatusObject([response,o]))
);
This is perfectly fine as well, but when you want to define your functions as an array and pipe them to create new functions you can no longer hard code functions in getDate.
Pipe (still called compose here) will pipe output of one function as input to another. Let's try an example of pipe and how it can be used to define different functions that do similar tasks and how you can modify the root implementation without changing the functions depending on it.
Let's say you have a data table that has paging and filtering. When table is initially loaded (root definition of your behavior) you set parameter page value to 1 and an empty filter, when page changes you want to set only page part of parameters and when filter changes you want to set only filter part of parameters.
The functions needed would be:
const getDataFunctions = [
[pipe([setPage,setFiler]),SET_PARAMS],
[makeRequest,MAKE_REQUEST],
[setResult,SET_RESULTS],
];
Now you have the behavior of initial loading as an array of functions. Initial loading looks like:
const initialLoad = (action,state) =>
pipe(getDataFunctions.map(([fn])=>fn))([action,state]);
Page and filter change will look like:
const pageChanged = action =>
pipe(getDataFunctions.map(
([fn,type])=>{
if(type===SET_PARAMS){
return setPage
}
return fn;
}
))([action,state]);
const filterChanged = action =>
pipe(getDataFunctions.map(
([fn,type])=>{
if(type===SET_PARAMS){
return setFiler
}
return fn;
}
))([action,state]);
That demonstrates easily defining functions based on root behavior that are similar but differ slightly. InitialLoad sets both page and filter (with default values), pageChanged only sets page and leaves filter to whatever it was, filterChanges sets filter and leaves page to whatever it was.
How about adding functionality like not making the request but getting data from cache?
const getDataFunctions = [
[pipe([setPage,setFiler]),SET_PARAMS],
[fromCache(makeRequest),CACHE_OR_REQUEST],
[setResult,SET_RESULTS],
];
Here is an example of your getData using pipe and thread with an array of functions (in the example they are hard coded but can be passed in or imported).
const getData = url => {
const thread = createThread();
return pipe([//array of functions, can be defined somewhere else or passed in
thread(urlToResponse,SAVE),//save the response
responseToObject,
objectWithDates,
thread(objectAndResponseToObjectAndStatusObject)//uses threaded value
])(url);
};
The array of functions is easy enough for JavaScript but gets a bit more complicated for statically typed languages because all items in the array have to be T->T therefor you cannot make an array that has functions in there that are threaded or go from a to b to c.
At some point I'll add an F# or ReasonML example here that does not have a function array but a template function that will map a wrapper around the functions.
Use async/await. That will make things much cleaner:
async function getData(endpoint) {
const res = await fetch(endpoint, {
method: 'GET'
})
const body = await res.json()
return {
status: res.status,
body
}
}
You also might want to add a try / catch block and a res.ok check to handle any request errors or non 20x responses.

Categories

Resources