Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
What is the best way to wrap this node.js snippet in a function?

I have a code example in this format:

someFunction(data)
                  .then(response => {
                        return response.text();
                  }).then(text => {
                        console.log(text)
                  }).catch(err => {
                        console.error(err)
                  });

I want to stuff this into my own function and call it through out my code.

let result = await callSnippet(myData);

This is what I've been doing... Is this the best way? Should I be using a promise here?

async callSnippet(data) {
    let response = null
    await someFunction(data)
                .then(  d=> { return d.text(); })
                .then(  d=> { response = {success:true,  result:d }; })
                .catch( d=> { response = {success:false, result:d }; })
    return response;
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You shouldn't be using both await and .then(). What you should do is:

async callSnippet(data) {
    let response = null;
    try{
        var d = await someFunction(data).text();
        response = {success: true, result: d};
    } catch(e){
        response = {success: false, result: e};
    }
    return response;
}

The await keyword retrieves the value from a Promise, so you can't use .then() on that value. However, you can achieve the same functionality by using a try...catch statement.

about 4 years ago · Juan Pablo Isaza Report

0

Typically if you are waiting to await things, you would await each step and not use then.

async callSnippet(data) {
  try {
    const response = await someFunction(data);
    const text = await response.text();
    return { success: true,  result: text };
  } catch (e) {
    return { success: false, result: e };
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!