node.js - 返回第一个满足条件的数组中的值
问题描述
抱歉,对 node.js 很陌生
我想从首先满足条件的数组中返回一个值。请参阅下面的最小示例:
var urlExists = require('url-exists');
arr = ['http://123123123.com/', 'https://www.google.com/', 'https://www.yahoo.com/']
const found = arr.find(url => urlExists(url, function(err, exists) { return exists } ));
// expecting google.com
不太确定如何urlExists(...)
评估true
。
解决方案
你可以在这里使用Promise。首先,您可以.map()
将您的 URL 数组指向一组 Promise,根据urlExists
给定 URL 是否调用错误来拒绝或解决。
一旦你有了一个 promise 数组,你就可以将它传递给一个Promise.all()
返回一个新 promise 的调用。当这个 Promise 解决时,它将包含一个 形式的数组[[url1, existsStatus1], ...]
,然后您可以使用.find()
它来查找第一次出现的地方existsStatus
是真的:
const urlExists = require('url-exists');
const arr = ['http://123123123.com/', 'https://www.google.com/', 'https://www.yahoo.com/'];
const urlPromise = Promise.all(arr.map(
url => new Promise((res, rej) => urlExists(url, (err, exists) => err ? rej(err) : res([url, exists])))
));
urlPromise.then((arr) => {
const [found] = arr.find(([,exists]) => exists) || [];
console.log(found); // URL found, undefined if nothing found
}).catch((err) => { // error with handling one of the URLs
console.error(err);
});
推荐阅读
- spring-integration - 在 spring 集成之外使用 spring 集成 lockregistry
- swift - 编辑 macOS 应用程序“关于”面板
- javascript - 如何使用 JWT 刷新令牌生成新的访问令牌
- powerbi - 如何从 Power BI 桌面中的度量中获取平均值
- javascript - 如何使用uploadcare上传多个文件
- javascript - array.push 是否深度复制?
- c - 输出 3x3 块“#”时遇到问题
- javascript - 角度保护功能
- c# - 使用 Switch 语句过滤 AC# LINQ 语句
- ms-access - MS Access 子窗体 HWnd 参考