CPak
CPak

Reputation: 13581

Return value in array that first satisfies condition

Sorry, very new to node.js

I want to return a value from an array that first satisfies a condition. See the minimal example below:

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

Not really sure how to have urlExists(...) evaluate to true.

Upvotes: 1

Views: 55

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50854

You can make use of Promises here. First, you can .map() your array of URLs to an array of Promises which either reject or resolve depending on whether calling urlExists errors or not for a given URL.

Once you have an array of promises, you can pass that into a call to Promise.all() which will return a new promise. When this promise resolves, it will contain an array of the form [[url1, existsStatus1], ...], which you can then use .find() on to find the first occurrence where existsStatus is true:

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

Upvotes: 2

Related Questions