首页 > 解决方案 > 返回第一个满足条件的数组中的值

问题描述

抱歉,对 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

标签: node.js

解决方案


你可以在这里使用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);
});

推荐阅读