Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading