Multiple Async/Await Pipes

:rocket: Hey there Tadabase Enthusiasts! :rocket:

I’m excited to share a quick video tutorial I’ve put together for you all. In this short clip, I’ll walk you through the process of making asynchronous JavaScript calls using the Tadabase pipes.

:movie_camera: Here’s what you’ll find in the video:

  • Pipes/Javascript feature
  • A brief guide to using async/await for efficient data handling
  • Tips and tricks for seamless integration

That’s it! No lengthy explanations, just a concise guide to help you master async/await with Tadabase. Check out the video now and level up your Tadabase skills. :fire:

Video Explanation

Fake Store

Here is code example:


let timerInterval;
const recordIds = [];

// **********************************************

//Extract URL Parameters
$.urlParam = function(name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  if (results == null) {
    return null;
  }
  return decodeURIComponent(results[1]) || 0;
};

function runNotifications() {
    setTimeout(function(){
        $('.send-email').html('<strong>✅&nbsp;Send Email Notification</strong>');
    }, 2000);
    setTimeout(function(){
        $('.redirect').html('<strong>✅&nbsp;Redirect</strong>');
        window.location.href = '/fake-store';
    }, 4000);
}

// **********************************************

function alertPaymentProcess(){
    Swal.fire({
      title: 'Processing Payment!',
      html: 'I will close in <b></b> milliseconds.',
      timer: 4000,
      timerProgressBar: true,
      didOpen: () => {
        Swal.showLoading();
        const b = Swal.getHtmlContainer().querySelector('b');
        timerInterval = setInterval(() => {
          b.textContent = Swal.getTimerLeft();
        }, 100);
      },
      willClose: () => {
        clearInterval(timerInterval);
      }
    }).then((result) => {
      /* Read more about handling dismissals below */
      if (result.dismiss === Swal.DismissReason.timer) {
          // Show the loading gif/spinner
        TB.showLoading();
      }
    });
}

// **********************************************

// Promise wrapper for TB.triggerPipe
function paymentGateway(params) {
  return new Promise((resolve, reject) => {
    TB.triggerPipe('eyJpdiI6Imw0dkRMRU1ObGZ6blFPd0Z0UDFCY2c9PSIsInZhbHVlIjoicFB0eEd4eU9yU2xCS3RjcUZmZ2pvWk05S3B3Mm1za2hraTRMc1VhRzFWZz0iLCJtYWMiOiJhMDYxOGQwNzNmZWE0ZmU5Y2NlYzM1YjVlYzMwMWVkMDM4Njg5ZjU5YzM3YTBjY2I4NzI5NGJmNjk1NDBhZTVhIn0=',
      params,
      function(type, response, xhrRespone) {
        if (type === 'success') {
          resolve({type, response, xhrRespone});
        } else {
          reject({type, response, xhrRespone});
        }
      }
    );
  });
}

// Async function to execute the pipe
async function processPayment(amount) {
  try {
    const params = {
      Name: '{loggedInUser.Name}',
      Card: '1111-2222-3333-4444',
      Expiration: '09/29',
      CVV: '048',
      Amount: amount
    };
    
    const result = await paymentGateway(params);
    console.log('Payment was successful:', result.response);
    $('.process-payment').html('<strong>✅&nbsp;Processing Payment</strong>');
    
  } catch (error) {
    console.log('Payment failed:', error);
  }
}

// **********************************************

// Promise wrapper for TB.triggerPipe
function orderGateway(params) {
  return new Promise((resolve, reject) => {
    TB.triggerPipe('eyJpdiI6Im9odjRLeVwvYm9obkxNc1p5VXU2dFRBPT0iLCJ2YWx1ZSI6IkROc2ZYNk9CNzdCQUhndVRQT1JSSjk3K2FJZ1NyN0dYNGtpdXhKZVJjV0E9IiwibWFjIjoiYjY5MDg2Y2IzMTI5NmI5OGRjYzIyYjcxNmFmNGFlMTY3ODY2ZGEwOWViMThkNDRhYzkxMzNjN2YzYWMxOTEwNSJ9',
      params,
      function(type, response, xhrRespone) {
        if (type === 'success') {
          resolve({type, response, xhrRespone});
        } else {
          reject({type, response, xhrRespone});
        }
      }
    );
  });
}

// Async function to execute the pipe
async function processOrder() {
  try {
    const params = {
        tableId: 'lGArg7rmR6',
        field_id: 'field_42',
        field_val: 'DVWQWRNZ49'
    };
    
    const result = await orderGateway(params);
    console.log('Order was successful:', result.response);
    $('.create-order').html('<strong>✅&nbsp;Create Order</strong>');
    processCart(result.response.recordId);
  } catch (error) {
    console.log('Order failed:', error);
  }
}

// **********************************************

// Promise wrapper for TB.triggerPipe
function updateCart(record, orderId) {
  return new Promise((resolve, reject) => {
      TB.triggerPipe('eyJpdiI6InA4U2grN0J1ZTloWUh3RGNiQWwyVkE9PSIsInZhbHVlIjoiQzlZZXlzdjRTb0szeGpQNGpxbjRiaVZ4SVdpRGVDVjZTYmw5NWhtOWM0Zz0iLCJtYWMiOiI1YmNkMWIxYTAzZmMzODY3NzA2ZTgyNmM0YzY3MDUxNDQ3MDZhNDQzMTdjNzUzOWRiZjhlOTJhNjI1ZWJkODg2In0=', 
        	{tableId: 'eykNOvrDY3',field_id: 'field_53',field_val: orderId,recordId: record},
        	function(type, response, xhrRespone) {
                if (type === 'success') {
                  resolve({type, response, xhrRespone});
                } else {
                  reject({type, response, xhrRespone});
                }
            }
        );
  });
}

// Async function to execute the pipe
async function processCart(id) {
  try {

    recordIds.forEach(record => {
      updateCart(record, id);
    });
    
    console.log('Cart Update was successful');
    $('.update-cart').html('<strong>✅&nbsp;Updpating Cart</strong>');
    runNotifications();
  } catch (error) {
    console.log('Cart Update failed:', error);
  }
}

// **********************************************

// TB.render function
TB.render('component_7', async function(data) {
    
    //Call the loader Function
    alertPaymentProcess();
    //Extract Amount from URL
    var amount = $.urlParam('amount');
    // Call the async function
    await processPayment(amount);
    await processOrder();

});

// **********************************************

// TB.render function
TB.render('component_11', function(data) {
	const records = data.records;
	records.forEach(record => {
      recordIds.push(record.id);
    });
});

Remember to maintain that growth mindset, and stay tuned for more handy tips and tricks in the world of web development. Keep building, keep growing! :muscle::sparkles:

This video is sponsored by: @SafetyUniversity @ChTim @kruizf201
Providing solution to @slimpens request

5 Likes

Well done Kevin! Outstanding explanation and example.

~Adam

2 Likes

Hey @kruizf201 that’s a great video - kudos to you, you “know your onions” :onion: :onion: :onion:

2 Likes