Generate a collection of information by gathering metadata from Xray

I've been struggling to populate an array with metadata retrieved using Xray. The issue arises when the function is called by an API endpoint on my server to fetch links from my application.

My main challenge seems to be related to promises, as there is a delay in scraping the metadata and I'm unable to make the function wait until all data has been collected before proceeding. I wonder if my confusion lies in understanding how Xray or promises work? Despite trying various approaches, including the following simple one:

  function createCollection() {
    Promise.all(rawLinks.map(function(link) {
      linksArray.push(xray(link, 'title')(function(error, title) {
        console.log(title);
        return title;
      }))
    }))
    .then(linksArray => {
      console.log(linksArray);
    });
  }

This method, while not the most sophisticated solution I've attempted, produces an array logged as "undefined" data first, followed by individual titles being logged.

Any assistance or guidance on where to focus my research would be greatly appreciated. At this point, I feel like I've tried everything and hit a dead end in finding a solution.

Answer №1

Finally figured it out, this script appears to be working perfectly!

  // organize links into an array of objects
  var rawLinks = links.split(', ');
  var linksArray = [];
  
  initializeCollection();

  function initializeCollection() {
    rawLinks.map(function(link) {
      var fillMetaPromise = new Promise(
        function(resolve, reject) {
          var test = xray(link, 'title')(function(err, title) {
            var data = { title: title, link: link };
            resolve(data);
          });
        })
        .then(data => {
          processData(data.title, data.link);
        });
    });
  }

  function processData(title, link) {
    var object = {
      link: link,
      title: title
    };

    linksArray.push(object);
    console.log(linksArray);
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Browserify to load the npm-module client-side for thepiratebay

I am currently facing an issue with my node.js server file. It successfully loads my site and runs JavaScript, but I encountered a problem when trying to include tpb = require('thepiratebay'); in the server.js file. Although it works fine in the ...

The process of transmitting messages back and forth between a popup script and a content script

I am in the process of developing a Chrome extension that involves sending data requests from a popup script to a content script (via a background script), analyzing the request on the content script, and then sending back a response (again through the bac ...

When the user presses either the refresh button or the back button, they will be redirected

After the user presses refresh or uses the browser back button, I need to redirect them to a specific page in order to restart the application. My JavaScript code is as follows: var workIsDone = false; window.onbeforeunload = confirmBrowseAway; function ...

Differences between visibility property manipulation in HTML and JS

One issue I am facing is that when I add a hidden property to a button in the HTML, it remains invisible. <button id="proceed_to_next_question" hidden> Next Question </button> However, if I remove the hidden property and include the following ...

Using a varied version of NPM during the creation of a React application

Whenever I attempt to create the initial React tutorial application using powershell, an error message shows up: "You are utilizing npm version 2.15.12 which means that the project will be set up with an old unsupported toolset". "Please upgrade to npm 3 ...

Handling multiple requests in Node.js allows for efficient and scalable execution

In NodeJs, it operates as single-threaded where there is one main thread responsible for handling our operations and delegating asynchronous tasks to separate threads. Therefore, the use of callbacks leads to offloading the current task to another thread. ...

Change the boxShadow and background properties of the material-ui Paper component

I am currently referencing their documentation found at this link in order to customize default Paper component properties. Below is the code snippet I have: import { styled } from '@mui/material/styles'; import { Modal, Button, TextField, Grid, ...

Utilizing Axios for Vue Multiselect on select/enter Event

I have successfully implemented a Vue Multiselect feature that retrieves options from my database using an axios call. This functionality works great as it allows users to select existing options or add new ones to create tags. While this setup is working ...

Utilizing a Chrome packaged app to interact with a local sqlite database through reading and writing operations

Is it feasible to access and manipulate a local sqlite database from within a Chrome packaged app? I am currently able to work with a locally stored JSON file for my app data, but now I also require the functionality to interact with a sqlite database in ...

Enhancing React Performance: Storing Component Identity in Redux State

Can I safely pass this to a Redux action creator from a component defined using React.createClass? In my code, I have created the following reducer: const unsavedChangesProtectionReducer = handleActions({ [ENABLE_UNSAVED_CHANGES_PROTECTION]: (unsaved ...

Execute JavaScript/AJAX solely upon the selection of a button

Currently, my script is being executed immediately after the page loads and then again after a button click. Is there any way to modify it so that the script waits until I click the button before running? As far as I understand, this code runs asynchronous ...

What is the process for executing a function if the Materialize.css autocomplete feature is not chosen?

Is it feasible to create a function that triggers only when a user does not select an option from Materialize.css autocomplete feature? My goal is to automatically populate an email field with a predefined value based on the user's selection in anothe ...

Baconjs exclusively retrieves the final debounce value

Below is a code snippet that showcases my current implementation: let watcher; const streamWatcher = bacon.fromBinder(sink => { watcher = chokidar.watch(root, { ignored: /(^|[\/\\])\../ }); watcher.on('all&a ...

How to place a stylish font over an image and recreate hover effects

I am looking to place social media icons below an image next to the photo's title, including Facebook, Twitter, Soundcloud, and Instagram. I want these icons to rotate along with the image when it is hovered over. HTML <div class="polaroid-image ...

Calendar Complete If a month has no scheduled events, the calendar will seamlessly move on to the next month

Is it possible to set up full calendar so that it automatically advances to the next month if there are no events scheduled? For example, if there are no events in June or all events have already taken place, can the calendar automatically move on to July ...

``Is it possible to iterate through a collection of objects using a loop?

I am facing an issue with updating a global array that contains objects, where each object includes another array. My goal is to update the main array with values from the arrays within the objects following a specific logic! generalArray = [{name:String, ...

Using SaltStack to install an NPM package with the --unsafe-perm flag

Is it possible to enable the unsafe-perm setting as true during npm package installation? npm-pkgs: npm.installed: - names: - composer-cli - generator-hyperledger-composer I encountered a permission problem while attempting to install ...

Obtain access to global.window.localStorage within getServerSideProps

I have a component that receives props with data and renders the data. In my functionality within the getServerSideProps, I am attempting to retrieve data from localStorage. However, due to window being undefined, I am unable to do so. I have tried using ...

Knockout.js client-side validation system

Currently working on a sophisticated client-side web application and I'm in search of the perfect framework for handling validations. I experimented with JQuery validation plugin, but unfortunately it didn't integrate smoothly with knockout.js da ...

Unlocking the power of module augmentation in Typescript: Enhancing library models within your app domain

I currently work with two applications that share the same code base for their models. I am interested in developing and sharing a library model using inheritance in TypeScript. For instance, Pet extends Author. In my current Angular application, I need ...