PROMO JULIO en CVOSOFT United States Of America: 💎Calidad, 🔥Bonificaciones, 🥶Precios Congelados y MÁS!

 X 

✒️¿Cómo trabajar con código asíncrono en SAPUI5?

¿Cómo trabajar con código asíncrono en SAPUI5?

¿Cómo trabajar con código asíncrono en SAPUI5?

How to Work with Asynchronous Code in SAPUI5?

Asynchrony is one of the fundamental pillars of JavaScript. By understanding these concepts, we can apply them in our code to write better applications.

We can have input and output operations of the following types:

  • Synchronous and Blocking: The entire operation is done at once, blocking the execution flow. The thread is blocked while waiting, and the response is processed immediately after the operation is completed.
  • Synchronous and Non-Blocking: Similar to the previous type, but uses some polling technique to avoid blocking in the first phase. The call returns immediately, the thread is not blocked, and successive attempts are needed until the operation is complete. The response is processed immediately after the operation is finished.
  • Asynchronous and Non-Blocking: The request returns immediately to avoid blocking. A notification is sent once the operation is completed. The function that processes the response (callback) is then queued to be executed at some point in our application.

1 | Asynchronous Calls

Synchronous vs. Asynchronous calls refer to when the response will take place:

  • Synchronous: Often used interchangeably with 'blocking,' meaning that the entire input/output operation is executed sequentially, and we must wait for it to complete to process the result.
  • Asynchronous: The completion of the input/output operation is signaled later through a specific mechanism like a callback, a promise, or an event, making it possible for the response to be processed later. This behavior is non-blocking as the call returns immediately.

JavaScript was designed to be executed in browsers, handle network requests, and process user interactions while maintaining a fluid UI. Being blocking or synchronous would not help achieve these goals. Therefore, JavaScript has evolved to support asynchronous operations.

2 | The JavaScript Model

JavaScript uses an asynchronous, non-blocking model with an event loop implemented with a single thread for its input/output interfaces.

Is JavaScript synchronous or asynchronous?

JavaScript is inherently synchronous and single-threaded, meaning it can only execute one task at a time. However, to handle long-running operations like network requests without freezing the user interface, JavaScript utilizes asynchronous mechanisms. These mechanisms include callbacks, promises, and async/await, which allow JavaScript to initiate an operation and continue running other tasks until the operation completes.

Asynchrony is fundamental to JavaScript because it is a single-threaded programming language, meaning it can only execute one thing at a time. Imagine requesting data from an API; depending on the situation, the server may take a while to process the request, blocking the main thread and making the web page unresponsive. This is where asynchrony comes into play, allowing long network requests without blocking the main thread.

JavaScript uses an asynchronous, non-blocking model with a single-threaded event loop for input/output operations. This solution makes JavaScript highly concurrent despite using a single thread.

JavaScript is fundamentally synchronous and single-threaded, meaning it executes one task at a time in a sequential manner. However, to handle tasks that might take a long time to complete, such as network requests, JavaScript employs asynchronous mechanisms. These mechanisms include callbacks, promises, and async/await, enabling JavaScript to start an operation and continue running other tasks until the operation completes.

Understanding the Event Loop

The event loop is a crucial part of JavaScript's concurrency model. It allows JavaScript to perform non-blocking operations, even though it runs on a single thread.

  • Call Stack: JavaScript runtime maintains a call stack that keeps track of function calls. Functions are added to the stack when they are called and removed when they return.
  • Web APIs: Browsers provide Web APIs (e.g., setTimeout, XMLHttpRequest) that handle asynchronous operations outside the call stack.
  • Callback Queue: When an asynchronous operation completes, its callback is placed in the callback queue.
  • Event Loop: The event loop continuously checks the call stack and the callback queue. If the call stack is empty, the event loop pushes the first callback from the queue to the call stack.

This mechanism ensures that long-running operations do not block the main thread, allowing the UI to remain responsive.

Consider the following code to illustrate the event loop:

console.log("Start");

setTimeout(() => {
console.log("Timeout callback");
}, 1000);

console.log("End");

Here's what happens step-by-step:

  • console.log("Start") is added to the call stack and executed immediately, printing "Start" to the console.
  • setTimeout is added to the call stack and executed. It sets a timer for 1000 milliseconds and passes the callback function to the Web API. The setTimeout call then completes and is removed from the stack.
  • console.log("End") is added to the call stack and executed, printing "End" to the console.
  • After 1000 milliseconds, the Web API moves the setTimeout callback to the callback queue.
  • The event loop checks the call stack (which is now empty) and moves the setTimeout callback to the call stack.
  • The callback is executed, printing "Timeout callback" to the console.

3 | Asynchronous Patterns

Callback Function

A callback function is a first-class function passed to another function as a variable and executed at some point during the receiving function's execution. Example of a Callback:

const myCallback = () => console.log("Hello World with delay!");
setTimeout(myCallback, 1000);

In this example, setTimeout is an asynchronous function that schedules the execution of a callback once a specified amount of time has passed (1 second in the example above). It fires a timer in an external context and registers the callback to be executed once the timer finishes. In summary, it delays an execution for at least the specified amount of time.

Promises

The Promise object is used for asynchronous communications. A promise represents a value that might be available now, in the future, or never. A promise is an object representing the eventual completion or failure of an asynchronous operation.

Why use Promises?

Promises allow us to write asynchronous code in a chainable manner that reads like sequential code, i.e., line after line instead of callbacks within callbacks.

Unlike callback functions, a promise comes with some guarantees:

  • Callback functions will never be called before the current execution of the JavaScript event loop is finished.
  • Callback functions added with .then will be called after the success or failure of the asynchronous operation.
  • Multiple callback functions can be added by calling .then multiple times to be executed independently in the order they were inserted.

The most immediate benefit of promises is chaining. A common need is to execute two or more asynchronous operations in sequence, where each subsequent operation starts when the previous one succeeds, using the previous step's result. We achieve this by creating a promise chain. Example of a Promise:

let promise = new Promise((resolve, reject) => {
let success = true; // Simulate success or failure
setTimeout(() => {
if (success) {
resolve("Operation successful!");
} else {
reject("Operation failed!");
}
}, 1000);
});
promise.then(result => {
console.log(result); // Operation successful!
return "Next operation";
})
.then(nextResult => {
console.log(nextResult); // Next operation
})
.catch(error => {
console.error(error); // If any promise is rejected
});

4 | Promises

A promise can be in one of the following states:

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: Means the operation completed successfully.
  • Rejected: Means the operation failed.

A pending promise can be fulfilled with a value or rejected with a reason (error). When either happens, the methods associated with the promise's then method are called.

Example:

Imagine ordering food at a fast-food restaurant. When you finish paying for your food, you receive a ticket with a number. When that number is called, you can go pick up your food. That ticket is your promise, indicating that eventually, you will have your food, but you don't have it yet. When your number is called, it means the promise is fulfilled. However, a promise can either be fulfilled successfully or fail.

In our case, a possible error might be that the restaurant has run out of food. When your number is called, two things can happen:

  • Your order is resolved, and you get your food.
  • Your order is rejected, and you get a reason why.

When we create a promise, it receives a function with two parameters: a reference to the success function and a reference to the error function.

let orderFood = new Promise((resolve, reject) => {
let isFoodAvailable = true; // Simulate food availability
setTimeout(() => {
if (isFoodAvailable) {
resolve("Your food is ready!");
} else {
reject("Sorry, we're out of food.");
}
}, 2000);
});
orderFood.then(message => {
console.log(message); // Your food is ready!
})
.catch(error => {
console.error(error); // Sorry, we're out of food.
});

5 | Asynchronous OData Calls

One of the most straightforward examples of asynchronous code in SAPUI5 is OData calls. The code inside the success handler is executed when it returns the result, and any errors are handled inside the error handler. This is somewhat similar to what we have seen with promises.

Promises are objects that allow us to associate actions that will be executed asynchronously, depending on the result of another triggering action. They allow asynchronous methods to return values as if they were synchronous by returning a promise that will provide a result in the near future.

Here's how to wait for a request from an OData service. In the read method of the service, which is executed asynchronously, we pass two methods: one to execute if the call was successful and the other if it failed:

var oModel = new sap.ui.model.odata.v2.ODataModel("/path/to/service");

oModel.read("/EntitySet", {
success: function(oData, response) {
console.log("Success: ", oData);
},
error: function(oError) {
console.error("Error: ", oError);
}
});

6 | Enabling Asynchronous Loading in Bootstrap

To further enhance the performance of our SAPUI5 applications, we can enable asynchronous loading during the bootstrap process. This allows our application to load resources asynchronously, ensuring that the main thread remains unblocked and the user interface remains responsive.

To enable asynchronous loading, set the async property to true in the bootstrap configuration:

<script id="sap-ui-bootstrap"
src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js"
data-sap-ui-theme="sap_belize"
data-sap-ui-libs="sap.m"
data-sap-ui-async="true">
</script>

Enabling asynchronous loading helps to keep the UI responsive by loading resources in the background, allowing the application to be more efficient and user-friendly.


 

 

 


Sobre el autor

Publicación académica de Jaime Eduardo Gomez Arango, en su ámbito de estudios para la Carrera Consultor en SAP Fiori.

SAP Expert


Jaime Eduardo Gomez Arango

Profesión: Ingeniero de Sistemas y Computación - España - Legajo: SW34C

✒️Autor de: 149 Publicaciones Académicas

🎓Cursando Actualmente: Consultor en SAP Fiori

🎓Egresado de los módulos:

Disponibilidad Laboral: FullTime

Presentación:

Ingeniero de sistemas y computación con 8 años de experiencia el desarrollo frontend & backend (react/node) y en cloud (aws), actualmente desarrollando habilidades en sap btp, ui5, abap y fiori.

Certificación Académica de Jaime Gomez

✒️+Comunidad Académica CVOSOFT

Continúe aprendiendo sobre el tema "¿Cómo trabajar con código asíncrono en SAPUI5?" de la mano de nuestros alumnos.

SAP Senior

Código asincrónico thread Síncrono Asíncrono javaScript es síncrono aunque haya tareas asíncronas con Ajax event loop timer promise .then pending fulfilled rejected promesa como un ticket llamadas OData asincrónica odataModel.read async success error Bootstrap rootView manifest.json data-sap.ui-async loop de eventos javascript solo ejecuta una cosa a la vez

Acceder a esta publicación

Creado y Compartido por: Enrique Gomez

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Expert


How to Work with Asynchronous Code in SAPUI5? Asynchrony is one of the fundamental pillars of JavaScript. By understanding these concepts, we can apply them in our code to write better applications. We can have input and output operations of the following types: Synchronous and Blocking: The entire operation is done at once, blocking the execution flow. The thread is blocked while waiting, and the response is processed immediately after the operation is completed. Synchronous and Non-Blocking: Similar to the previous type, but uses some polling technique to avoid blocking in the first phase. The call returns immediately, the thread is not blocked, and successive attempts are needed until the operation is complete. The response is processed...

Acceder a esta publicación

Creado y Compartido por: Jaime Eduardo Gomez Arango / Disponibilidad Laboral: FullTime + Carta Presentación

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Senior

Javascript JavaScript es un lenguaje de programación de alto nivel creado por Brendan Eich en 1995, originalmente destinado a mejorar la interactividad en páginas web. A lo largo de los años, ha evolucionado y se ha expandido a diversas áreas de desarrollo, tanto en el lado del cliente como en el lado del servidor. Algunas características clave de JavaScript incluyen su naturaleza interpretada, orientación a objetos, dinamismo y tipado débil. Se ejecuta directamente en los navegadores web y es esencial para manipular el Document Object Model (DOM), permitiendo la interacción con elementos HTML y CSS. El lenguaje también se ha extendido al lado del servidor a través de plataformas...

Acceder a esta publicación

Creado y Compartido por: Claudio Marcelo Hermann / Disponibilidad Laboral: FullTime

*** CVOSOFT - Nuestros Alumnos - Nuestro Mayor Orgullo como Academia ***

SAP Senior

las llamdas asincronicas Podeos tener las siguientes operaciones de entrada y salida Sicronas Bloqueante Sicronas Np-bloqueantes asicronas No-bloqueantes Javascript utiliza un modelo asincrono no-bloqueante con un loop de eventos implementado con un unico theard para sus interfaces de entrada/salida La funcion callback: una funcion callback de primer nivel que se pasa a otra funcion como variable y esta es ejecutada en algun punto de la ejecucion de la funcion que la recibe Las Promesas una promesa representa un valor que puede estar disponible, ahora en el futuro o nunca. una promesa se encuentra en uno de los siguientes estados Pendiente (pending) Cumplida (fulfilled) Rechazada (rejected) La configuracion mas importante...

Acceder a esta publicación

Creado y Compartido por: Detriana Barrios / Disponibilidad Laboral: FullTime + Carta Presentación

 


 

👌Genial!, estos fueron los últimos artículos sobre más de 79.000 publicaciones académicas abiertas, libres y gratuitas compartidas con la comunidad, para acceder a ellas le dejamos el enlace a CVOPEN ACADEMY.

Buscador de Publicaciones:

 


 

No sea Juan... Solo podrá llegar alto si realiza su formación con los mejores!