Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
How Do I Modify My Code to be Asynchronous?

Below, I have written a function that takes an array and a key to search and count the number of times the key matches an element in an array. I am attempting to modify my function to count the number of matches asynchronously but don't know how to best go about it. Any insight or examples would be greatly appreciated.

My Code:


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 Respuestas
Responde la pregunta

0

Use Promise

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 Denunciar

0

You can return a promise from any synchronous function by converting it to an asynchronous function using the async keyword:

/** 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 Denunciar

0

async/ await

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda