Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}

>Solution :

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 };
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading