I need a javascript function that receives a method, and calls that method on an object created inside the function.
const callMethod = myMethod => {
someObject.myMethod();
}
I need this because I want to make a function that makes an HTTP request via fetch, and specify which method to call after getting the response from the fetch, where the options are: .json(), .text(), .blob(), .formData() or .arrayBuffer()
This is my code:
const sendPost = (url, bodyObj) => {
return new Promise(async (resolve, reject) => {
try {
const settings = {
method: "POST",
headers: {"Content-Type":"application/json"},
body: JSON.stringify(bodyObj)
}
let req = await fetch(url, settings);
// Here I'm forcing the .json() method, I want it to be able to choose between .json(), .text(), etc. when calling this function:
let res = await req.json();
return resolve(res);
} catch (e) {
return reject(e);
}
});
}
I have tried this, but it didn't work:
const sendPost = (url, bodyObj, func) => {
// ...
let req = await fetch(url, settings);
let res = await req.func();
// ...
}
sendPost("some url", {some object}, Response.json); // TypeError: req.func is not a function
I think the easiest way to do this is to pass a string with the name of the method I want to use, and then decide which method I want to call using conditionals. But I would like something more robust, which allows passing the pointer to an actual method, since the content of a string can be misspelled.
someObject, response => response.json());TypeScript (or, to a lesser extent, JSDoc) helps avoid misspelling typos too.funccarries a string value like'json'or'text'then result will be processed like ...let res = await req[func]();...but in case the OP passes real method references then a function'scallmethod is the to be chosen tool ...let res = await func.call(req);...And in case one is not sure aboutreqthen ...await req?.[func]?.()for the former case.