[英]How Do I Modify My Code to be Asynchronous?
下面,我寫了一個 function ,它接受一個數組和一個鍵來搜索並計算鍵與數組中元素匹配的次數。 我正在嘗試修改我的 function 以異步計算匹配數,但不知道如何最好地處理 go。 任何見解或示例將不勝感激。
我的代碼:
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));
使用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));
您可以通過使用async
關鍵字將其轉換為異步function 從任何同步 function 返回 promise:
/** 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
異步/等待
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.