1656766800
Esta publicación no trata sobre Promises, async/await o la naturaleza de subproceso único de Javascript. Si quieres saber sobre estos temas, entra aquí , aquí o aquí .
Este artículo trata sobre la función Promise.all() y cómo reunir funciones o tareas que se ejecutan de forma independiente en un hermoso resultado.
Como suele ser el caso, un ejemplo o caso de uso hace maravillas.
El objetivo principal de nuestra aplicación Ayrshare es proporcionar una API para publicar en varias redes sociales, como Twitter, Instagram, Facebook y LinkedIn.
Un usuario realizará una llamada API (RESTful o a través de un paquete de cliente) con el texto de la publicación, la imagen y la lista de redes para enviar la publicación. La API devuelve el éxito o el error resultante de cada red como una matriz de resultados.
Sin embargo, hay complejidad detrás de escena.
Cada red tiene sus propios requisitos de autorización, flujo de trabajo y seguridad. Por ejemplo, si adjunta una imagen a la publicación, Twitter requiere que primero cargue la imagen, espere a que se complete su procesamiento y envíe la ID de medios devuelta en su nueva llamada de estado de actualización a Twitter. Los tiempos varían, pueden ocurrir errores para algunos y no para otros, y se agregan nuevas redes todo el tiempo. Pero desde la perspectiva del usuario final, enviaron la publicación y los resultados se devuelven de inmediato.
Aquí hay una imagen ( descripción general de la pila tecnológica de Firebase ):
Queremos ejecutar todas las publicaciones de la red en paralelo y recopilar los resultados para devolverlos a la persona que llama. A medida que aumenta la cantidad de redes, lo ideal es que no tomemos más tiempo que la red más larga.
El problema al que nos enfrentamos es que si cada llamada de función de red es asíncrona, cada función se completará en momentos diferentes y no podremos devolver los resultados en una sola respuesta.
Si tiene un problema similar, Promise.all() es su solución.
Promise.all() "toma una iteración de promesas como entrada y devuelve una sola Promise
que se resuelve en una matriz de los resultados de las promesas de entrada".
En otras palabras, si llama a varias funciones asíncronas, puede esperar hasta que todas se resuelvan y capturen su salida en una matriz.
Veamos un ejemplo sencillo:
const getSquare = async (x) => Math.pow(x, 2);
const printSquares = async () => {
const nums = [1, 2, 3, 4, 5];
const promiseArray = nums.map(x => getSquare(x));
console.log(promiseArray);
};
printSquares();
printSquare itera sobre una matriz de enteros y cuadrados cada uno. Llamar a getSquare devuelve una promesa porque la convertimos en una función asíncrona al agregar la palabra clave asíncrona ; técnicamente, no necesitamos asíncrona ya que la función Math.pow es síncrona.
ElpromiseArray es una matriz de promesas que esperan ser resueltas. Cuando imprimimos el promiseArray :
[
Promise { 1 },
Promise { 4 },
Promise { 9 },
Promise { 16 },
Promise { 25 }
]
Cierra, pero ¿qué pasa con esas “Promesas”? Bueno, como se mencionó anteriormente, la matriz se compone de Promesas que esperan ser resueltas. Se pueden resolver fácilmente con Promise.all():
const getSquare = async (x) => Math.pow(x, 2);
const printSquares = async () => {
const nums = [1, 2, 3, 4, 5];
const promiseArray = nums.map(x => getSquare(x));
const results = await Promise.all(promiseArray);
console.log(results);
};
printSquares();
y los resultados:
[ 1, 4, 9, 16, 25 ]
¡Perfecto! También se mantiene el orden de los resultados.
Tenga en cuenta que debemos esperar en Promise.all() ya que devuelve una Promesa que debe resolverse.
Para aquellos que tienen curiosidad, aquí hay un ejemplo real del código de Ayrshare que se publica en todas las redes:
/**
* Post to social networks
*/
const postNetworks = NETWORKS.map((net) => {
return platforms.includes(net.type)
? net.func(auth[net.type], post, urls, id, {...})
: [];
});
const processedSocial = await Promise.all(postNetworks);
A menudo se piensa que Promise.all() se ejecuta en paralelo, pero este no es el caso.
Paralelo significa que haces muchas cosas al mismo tiempo en varios subprocesos.
Sin embargo, Javascript tiene un solo subproceso con una pila de llamadas y un montón de memoria. Es un lenguaje asíncrono , sin bloqueos. Esto significa que Javascript no se ejecuta en paralelo, sino que ejecuta solo una función/Promesa a la vez. Si el subproceso único tiene que esperar algo, como el retorno de una llamada http, pasará a otra función hasta que se complete el retorno.
En el caso de nuestra matriz de Promesas, cada Promesa se manejará una a la vez, pero Javascript cambiará entre cada una si el procesamiento necesita esperar. Si bien el orden de resolución de Promise en Promise.all() puede variar según el bloqueo, el resultado final será una matriz de resultados ordenados
Fuente: https://www.ayrshare.com/the-power-of-javascript-promise-all/
1602406920
Promises in JavaScript are used to handle asynchronous operations by keeping track of whether a certain event has happened. If that certain event has taken place, it determines what happens next. Promises return a value which is either a resolved value or a reason why it’s rejected. They can handle multiple asynchronous operations easily and they provide better error handling than callbacks and events.
Callback: A callback is a function that is passed into another function as an argument to be executed later.
Events: Events provide a dynamic interface to a WebPage and are connected to elements in the Document Object Model(DOM), for example: onclick(), onmouseover() etc.
Pending: Before the event has happened, the promise is in the pending state.
Settled: Once the event has happened it is then in the settled state.
Fulfilled: Action related to the promise has succeeded.
Rejected: Action related to the promise has failed.
#javascript #javascript-development #javascript-tutorial #promises #javascript-tips
1590928341
Promise.allSetlled() is recently introduced in ECMA 2020.
Check out how it is different from Promise.all()
https://www.geekstutorialpoint.com/2020/05/promiseallsettled-vs-promiseall.html
#javascript #promise.all #promise.allsettled #ecma #promise #jquery
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1608520601
Welcome to my post about the JavaScript Promises. I hope it can be helpful since when we start programming it is difficult to enter the context.
Promises are one of the largest tools in the world of JavaScript that helps us to manage future situations in the flow of execution of a program.
The promises originated in the realm of functional programming, generally to handle asynchronous programming. In short, they allow us to define how data that will only be available in the future will be treated, specifying what will be done with that data later.
The promises were introduced in the standard in ES6, the truth is that they have been used for a long time since several libraries had implemented them to solve their needs in a more elegant way.
The Promise object represents the eventual completion or failure of an asynchronous operation and its resulting value.
#programming #coding #javascript-promise #promises #javascript
1599295469
Let us understand term _Callback _by an real-world example: Suppose, you are calling to your Girlfriend (If you have) and she is busy in another call then she send message to you : “I am busy right now, Call back you later.!!”. After completing her work, she calls you back and this is what call back in JavaScript as well.
In JavaScript, When a function is executing (Girlfriend is talking with someone) then after function execution is completed another function is started for execution this is call back function.
Now you are thinking that its depend upon when, where you are calling function and all function call is “Call-back function”.
Here, _printWorld() _function is executed after _printHello() _complete its execution but this is not call-back function example because _printHello() _is not Asynchronous function. Suppose, _printHello() _prints after 1 Second then _printWorld() _executes first.
What if we want “Hello World” output when Asynchronous function is there. We can pass function as argument and calls it after _printHello() _complete its execution. Here below code snippet of how _function pass as argument _:
Callback function can be defined as a function passed by argument and executes when one function completes its execution.
Suppose, If you have API (Application Programming Interface) to get Students Roll numbers and select one of Roll number — getting that roll number’s data and print that data. We don’t have API to get students data so we are using _setTimeout() _Async function and getting roll number after 2s, We are also selecting one of roll number manually after 2s and print Roll number’s data after 2s. This can be done by call back function.
The program became complex and complex if we have too many things to do like Getting Students data, Selecting one of them student, get student’s roll number and get result by roll number then it become very complex. If you have any Error in this then debugging is also tedious task, this things is called “Callback Hell”, which is shape like “Pyramid Of Doom”.
To overcome with this problem, Promises is introduced in JavaScript. Promises has three states : Pending, Resolved, Reject. Promises is created by Constructor : new Promise(). It has one executor function which has two arguments (resolve, reject).
Promise object has three methods: then(), catch() & finally().
If Promise is successfully executed then its data is transferred through resolve function and if it has error then passed through reject function.
We have implemented same task which is done using call back function in Promises and its easily understandable However it is complicated compare to callback function but when you use promises for sometimes then it’s easy to implement.
In _getRollNumber(), _resolve method’s data is caught by then() functions arguments and reject method’s data is caught by catch() function. Here In Promises, Every task has different promises because of that it is easy to debug and readable compare to call back function. You can see that there is no shape like “Pyramid of Doom” in Promises. This is how Callback function is replaced by Promises.
Thank you for reading!
This article was originally published on Medium.com
#javascript-tips #advanced-javascript #javascript #callback-function #promises