Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
¿Cómo modifico mi código para que sea asíncrono?

A continuación, he escrito una función que toma una matriz y una clave para buscar y contar la cantidad de veces que la clave coincide con un elemento en una matriz. Estoy intentando modificar mi función para contar el número de coincidencias de forma asincrónica, pero no sé cuál es la mejor manera de hacerlo. Cualquier idea o ejemplo sería muy apreciado.

Mi código:

 function countMatches(arr, key) { var count=0; var i; for (i=0; i < arr.length; i++) { if(arr[i] == key) count=count+1; } return count; } let arr1 = [3, 2, 4, 6, 1, 1, 6, 8, 9]; console.log(countMatches(arr1, 6));
about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

usar promesa

 function countMatches(arr, key) { return new Promise((resolve) => { var count=0; var i; for (i=0; i < arr.length; i++) { if(arr[i] == key) count=count+1; } resolve(count); }); } let arr1 = [3, 2, 4, 6, 1, 1, 6, 8, 9]; countMatches(arr1, 6).then(result => console.log(result));

about 4 years ago · Santiago Gelvez Report

0

Puede devolver una promesa desde cualquier función síncrona convirtiéndola en una función asíncrona usando la palabra clave async :

 /** This is a sync function */ function getNumber1 () { return 42; } const n1 = getNumber1(); console.log({sync: n1}); // 42 /** This is an async function Notice the `async` keyword before `function` It automatically returns a promise which resolves to the value vvvvv */ async function getNumber2 () { return 42; } getNumber2().then(n2 => console.log({async: n2})); // 42

about 4 years ago · Santiago Gelvez Report

0

asíncrono/esperar

 async function countMatchesAsync(arr, key) { var count=0; var i; for (i=0; i < arr.length; i++) { if(arr[i] == key) count=count+1; } return await count; } let arr1 = [3, 2, 4, 6, 1, 1, 6, 8, 9]; countMatchesAsync(arr1, 6).then(console.log);
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!