Javascript Array.find和本机asyncawait/async/asyncawait/await解决方案
以下是:Javascript Array.find和本机asyncawait/async/asyncawait/await解决方案,javascript,Javascript,以下是: h = hs.find(h => await(isAvail(h))); 使用以下库: const async = require('asyncawait/async'); // async is used in the isAvail function to wrap it const await = require('asyncawait/await'); 如果没有老式的for循环数组,我似乎找不到一种优雅的方法。问题是,当find在数组上迭代时,wait似乎会阻止它。本
h = hs.find(h => await(isAvail(h)));
使用以下库:
const async = require('asyncawait/async'); // async is used in the isAvail function to wrap it
const await = require('asyncawait/await');
如果没有老式的for循环数组,我似乎找不到一种优雅的方法。问题是,当find在数组上迭代时,wait似乎会阻止它。本机等待不会发生这种情况,因为等待要求将函数声明为async,它本身返回一个必须等待的承诺,因此第四个
有人有什么想法吗?您尝试过:
h = hs.find(async h => await(isAvail(h)));
你需要一个for循环
下面是一个使用asyncwait
库的解决方案:
const async = require('asyncawait').async;
const await = require('asyncawait').await;
const find = async(function (arr, predicate) {
let check = false, result = null;
for (let elm of arr) {
check = await(predicate(elm));
if (check) {
result = elm;
break;
}
}
return result;
});
function isItBig (n) {
return Promise.resolve(n > 3);
}
let test = [1, 2, 3, 4, 5];
find(test, isItBig).then(console.log); //prints 4
这是一个几乎相同的解决方案,使用node.js最新版本中包含的本机异步/等待:
async function find (arr, predicate) {
let check = false, result = null;
for (let elm of arr) {
check = await predicate(elm);
if (check) {
result = elm;
break;
}
}
return result;
}
async function isItBig (n) {
return n > 3;
}
let test = [1, 2, 3, 4, 5];
find(test, isItBig).then(console.log); //prints 4
你能试着澄清你想要达到的目标,而不是仅仅说明你认为问题出在哪里吗?@E.Sundin Hi!我想删除第三方库。遍历数组,并在元素作为参数发送到异步函数(isAvail)后返回与“true”匹配的第一个元素。我想跳过对整个数组的迭代。如果异步运行,那么第一个元素
的概念非常模糊。@E.Sundin运行异步操作并不意味着同时运行它们。您可以按顺序运行它们,并且仍然可以从释放事件循环以进行其他操作中获益。@mysidestheyalegone您当然是对的。