Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

288
Visualizações
Pass method as parameter and use that method on an object (Javascript)

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are a few ways you could do this.

The way you've written it, if you were to pass in a string ("json"), then you could do this:

let response = await sendPost(..., "json");
    let res = await req[func]();

That finds the member with the name matching the string found in func.

You could also use a callback:

let json = await sendPost(..., response => response.json());
    let res = await func(req);

But the only thing you're doing after that point in your helper function is resolving errors and returning the result. It might make more sense to have your helper function return a Promise with the response in it.

let response = await sendPost(...);
let json = response.json();
    let res = await fetch(url, settings);
    return res;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda