Replace Callbacks by Async/Await

Replace callbacks by async/await for better readability and error handling in JavaScript.

You can query a model directly and test the results returned when using different parameter values with the Cloud console, or by calling the Vertex AI API directly.

Prompt Freeform

Refactor this JavaScript code to use async/await instead of callbacks for handling asynchronous operations. The goal is to improve code readability and error handling.

function fetchData(url, callback) {
  http.get(url, function(response) {
    let data = '';
    response.on('data', (chunk) => {
      data += chunk;
    response.on('end', () => {
      callback(null, data);
  }).on('error', (err) => {


async function fetchData(url) {
try {
const response = await new Promise((resolve, reject) => {
http.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
res.on('end', () => {
}).on('error', reject);
return response;
} catch (error) {
throw error; // Re-throw the error to be handled by the caller


  1. async function: We define the fetchData function as async, allowing us to use await within it.
  2. try...catch block: We wrap the asynchronous operation in a try...catch block to handle potential errors.
  3. Promise and await:
  4. We create a Promise that resolves with the data when the response is fully received.
  5. We use await to pause the execution of the function until the Promise resolves.
  6. Error handling:
  7. If an error occurs during the http.get request, the reject function of the Promise is called, causing the catch block to execute.
  8. We re-throw the error using throw error to propagate it to the caller.
  9. Return value: The fetchData function returns the fetched data if successful.


async function main() {
try {
const data = await fetchData('');
} catch (error) {
console.error('Error fetching data:', error);


Benefits of using async/await:

  • Improved readability: The code is more concise and easier to understand, as the asynchronous flow is more explicit.
  • Simplified error handling: The try...catch block provides a clear way to handle errors.
  • No callback hell: We avoid nested callbacks, making the code more maintainable.
  • Better control flow: The code execution is more predictable, as await pauses the function until the asynchronous operation completes.
Model: gemini-1.5-flash-001
Temperature: 1
Max output tokens: 8192
TopK: 40
TopP: 0.95