What is the best way to access the value of an object within an array of promises?

Within the Object, there are lookup keys that hold an Array of Promises. These Promises are used to conduct validations on a specified value.

Is it possible to access the value of full_name from within email?

const config = {
  full_name: [
    val => new Promise((resolve, reject) => resolve(val)),
    val => new Promise((resolve, reject) => resolve(val))
  ],
  email: [
    val => new Promise((resolve, reject) => resolve(val)),
    val => new Promise((resolve, reject) => reject(`${config.full_name.val}`)) // retrieve the value passed to full_name
  ]
}

Answer №1

config.full_name.val is not accessible because config.full_name consists of functions that return promises.

The functionality of these functions varies based on how they are called within a specific context, which is detailed in this explanation: https://jsfiddle.net/karlbateman/keqnrybq/.

Furthermore, since the validation component is separate from the main configuration module, direct access to formData is not feasible within the callbacks.

Nevertheless, you have the option to include a context parameter in your function callbacks to enable access to the formData, as demonstrated here: https://jsfiddle.net/odolha/tpn75570/

Take note of this line (in the validatorFn):

arr.push(config[field].map(cb => cb(formData[field], formData)))

Essentially, by passing the formData as a context parameter, it can be utilized later on:

(val, ctx) => new Promise((resolve, reject) => setTimeout(() => {
  reject(`${ctx.name} already exists.`) // mimics an HTTP request
}, 2000))

Answer №2

If you want to add a similar feature, you can do so with the following code snippet:

function createPromise(value, shouldPass = true){
  return new Promise(function(resolve,reject){
                       return shouldPass ? resolve(value) : reject(value);
                     });
}

var options = { 
    full_name: [createPromise, createPromise],
    email: [createPromise, createPromise]
};

options.full_name[0]("Thaddeus Jones")
      .then(result => options.email[1](result,false))
      .then(result => console.log("resolved by:", result))
      .catch(error => console.log("received error:", error));

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

Utilizing AngularJS for managing multiple controllers within a single file

As a beginner with angular JS, I am currently focusing on controllers and have created the script below. <!DOCTYPE html> <html> <head> <title>just learnin!</title> </head> <body> <div data-ng-app="clock ...

JavaScript and CSS animations out of sync in terms of timing

I've been encountering some issues. I have an array containing 5 lines of text that change with a timer, but it seems that the css timer animation might not be synced properly or my @keyframes slidesdown setup could be incorrect. The delay between te ...

Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list ...

Saving data in a CSV file on your local device using HTML5

Is it possible to utilize HTML5 for saving or writing data to a local file on the user's file system? I am curious about this functionality, especially since HTML5 now offers the capability to export data from the client and save it as a CSV file. If ...

Feeling unsure about the concepts of scoping and the "this"

Recently, I came across a code snippet at this source: : var CounterButton = function(el){ this.$el = $(el); this.counter = 0; this.bindEvents(); this.myVal = 1; } CounterButton.prototype.bindEvents = function(){ this.$el.click(this. ...

Using Primeng to implement pagination and lazy loading in a dataView

Looking for a way to search through product data with filters and display it using primeng dataview? Consider implementing pagination in your API that pulls products from the database page by page. Set the products array as the value in dataview so that wh ...

Combining two arrays by finding common elements

Currently, I am working on a project where I retrieve data from the server, and each piece of data has to adhere to a specific format: const DATA = [ { title: {title: 'Main dishes'}, data: [ {_id: 1, type: 'Pizza'}, ...

Is there a way to retrieve data from a sealed JSON object using JavaScript?

The data is being fetched from the API and here is the response object: { "abc": [{ "xyz": "INFO 1", "pqr": "INFO 2" }, { "xyz": "INFO 3", "pqr": "INFO 4" } ] } We are lookin ...

Tab switch or application switch?

Is there a way to distinguish between different browser events in the following scenarios? When the user clicks on another tab within the same browser, causing my tab to be hidden and should pause. When they switch to another application, with my tab ...

Changing HTML lists into JSON format

I am facing a slight issue with my HTML template while trying to convert it to JSON. My goal is to convert a list of HTML messages into JSON format. I appreciate your assistance in advance. HTML Template <div class="message"> <div class="mes ...

Basic JavaScript Calculator Utilizing JQuery

I have been diligently working on a Javascript Calculator for quite some time now. The CSS and HTML elements seem to be in order. However, the calculator is only functioning properly for sevens and division operations! While the input for other numbers g ...

Capturing user inputs in PHP or AJAX

Is there a way to capture keystrokes on a web page regardless of where the user is focused? For example, if someone has the webpage open and they press '1', can it trigger an action? And if they press '2', can something else happen wit ...

What is the process for changing the value of a specific data point within an integer array in C++ by utilizing pointers?

In my class assignment, I successfully demonstrated manipulating an array with pointers by outputting a value. However, I am now stuck on the second part of the task. The challenge involves outputting ar[0][3] using the pointer p with the given code snippe ...

Instead of returning a variable, opt for sending a new HTML page using Express and axios post request

Is there a way to verify username and password using axios with a post request? Here is my code snippet: function axiosCall() { axios.post('/login', { username: document.getElementById("username").innerText, password ...

Host image previews on the server using Dropzone.js

I'm currently utilizing Dropzone.js along with Angular.js for image uploads. However, I haven't been able to figure out a way to upload thumbnails to my server. .dropzone({ url: "/gallery/add", maxFilesize: 100, paramName: "up ...

Dynamically Exporting Node Modules

// custom-exports.js exports.createCustomExports = (exportObject) => { module.exports = exportObject for (const exportItem in exportObject) { exports[exportItem] = exportObject[exportItem] } } // calculations.js const { createCustomExports } = ...

Is it possible to utilize the Vuejs router routes array to dynamically generate a navigation menu?

Below is the code I am using to set up VueJS routes and pass them into a router: export const routesArray = { routes: [ { path: '/', name: 'Add Stash', component: Form }, { path: '/log', ...

Creating a unique HTML id using an evaluated expression

My goal was to create a minimalist version of the classic game "tic tac toe" using AngularJS. To achieve this, I had to come up with a unique solution by assigning each button a distinct ID (f+i). HTML <table> <tr ng-repeat="f in [5,10,15]"& ...

Utilize a chrome extension to showcase specific content on designated webpages through the use of

I'm currently working on creating a Chrome extension for Pinterest integration. After referencing some examples from the Chrome extension demo (specifically one that displays an icon in the omnibox when the URL contains a 'g'), I made modif ...

Challenge with PHP mail function in sending emails

I run a website and have a "Contact" section where users can fill out a form to reach me. The form is a basic one with its action being a php page. Here is the php code: $to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4 ...