Is there a way to extract both a and b from the array?

I just started learning programming and I'm currently working on creating an API call to use in another function. However, I've hit a roadblock. I need to extract values for variables a and b separately from the response of this API call:

import axios from "axios";

async function main() {
  await axios
    .get('https://api.blocknative.com/gasprices/blockprices?confidenceLevels=99', {
      headers: {
        Authorization: 'key'
      },
    })
    .then(function(response) {
      const a = response.data.blockPrices[0].estimatedPrices[0].maxFeePerGas;
      const b = response.data.blockPrices[0].estimatedPrices[0].maxPriorityFeePerGas;
      return [a, b]
    });
};

main().catch(console.error);

Can anyone guide me on how to achieve this? I've looked into topics like scope, block, and destructuring but I'm still unable to find a solution. Thank you for your assistance!

Answer №1

If you make the main function return a promise and handle its resolve, you can access variables a and b.

import axios from "axios";

function main() {
  return await axios.get(
    "https://api.blocknative.com/gasprices/blockprices?confidenceLevels=99",
    {
      headers: { Authorization: "key" },
    }
  );
}
main()
  .then(function (response) {
    const a = response.data.blockPrices[0].estimatedPrices[0].maxFeePerGas;
    const b =
      response.data.blockPrices[0].estimatedPrices[0].maxPriorityFeePerGas;
    return [a, b];
  })
  .catch(console.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

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

Searching for image labels and substituting the path string

Upon each page load, I am faced with the task of implementing a script that scans through the entire page to identify all image src file paths (<img src="/RayRay/thisisianimage.png">) and then add a specific string onto the file paths so they appear ...

Encountering a Hydration Error with Next.JS and MDX-Bundler when a MDX Component Adds Extra New Lines to its Children

Currently, I am incorporating next.js + mdx-bundler into my project. There is a simple component that I frequently use in my mdx files. Everything runs smoothly with the following code: Mdx is a great <Component>format and I like it a lot</Compon ...

New from Firefox 89: The afterprint event!

Having an issue with this fragment of code: const afterPrint = () => { this.location.back(); window.removeEventListener('afterprint', afterPrint); }; window.addEventListener('afterprint', afterPrint); window.print(); I&apos ...

Need to monitor a Firebase table for any updates

How can I ensure my Angular 2 app listens to changes in a Firebase table? I am using Angular2, Firebase, and TypeScript, but the listener is not firing when the database table is updated. I want the listener to always trigger whenever there are updates or ...

I am attempting to retrieve the aria-expanded value using JavaScript, however, I keep receiving an "undefined" response

I'm attempting to dynamically change the class of a <span> element based on the value of the attribute aria-expanded. However, I am encountering an issue where it returns "undefined" instead of the expected value of true or false. Below is the ...

TinyMCE is substituting the characters "<" with "&lt;" in the text

I am currently using Django with placeholder tags: I am attempting to insert a flash video into my TinyMCE editor, but it is replacing the '<' symbol with < in the code, preventing it from loading properly and only displaying the code. I hav ...

Leveraging Class Types with Generics

Take a look at this example: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics To make it work, I just need to call a static method before instantiation. Let's adjust the example like this: class BeeKeeper { ...

Having trouble getting the .toggle() function with classList to work on one element, despite working fine on others

I've been struggling to apply a class to an HTML element when I click on another element of the page. Despite numerous attempts, it just doesn't seem to work for me. Let's take a look at my code: HTML Code: <div class="container&qu ...

Using ReactJS to transform my unique array into an object before appending it to a list

Here is the array I am working with: [{…}] 0: {id: 2, createdAt: "2021-06-11T10:13:46.814Z", exchangedAt: "2021-06-11T08:04:11.415Z", imageUrl: "url", user: "user", …} 1: .... 2: .... 3: .... .... length: 5 __pro ...

Is it possible for me to declare attributes using a function object in a single statement?

Given an object obj, the following two-line statements can be defined: var obj ={} //this is an object obj.isShiny = function () { console.log(this); return "you bet1"; }; These two lines can be combined into a one-line statement ...

Display the initial three image components on the HTML webpage, then simply click on the "load more" button to reveal the subsequent two elements

I've created a div with the id #myList, which contains 8 sub-divs each with an image. My goal is to initially load the first 3 images and then have the ability to load more when clicking on load more. I attempted to follow this jsfiddle example Bel ...

When attempting to set a variable type using ":URL", an error is generated

When I created a file named "test.ts" in VSCode, I included the following code: var data = "https://a.b.c/d/e/f"; var url = new URL(data); console.log(url.protocol); After pressing F5, the output was "https:". However, when I added a type declaration like ...

Using an External JavaScript Library in TypeScript and Angular 4: A Comprehensive Guide

My current project involves implementing Google Login and Jquery in Typescript. I have ensured that the necessary files are included in the project: jquery.min and the import of Google using <script defer src="https://apis.google.com/js/platform.js"> ...

Analyze and tally occurrences in two arrays

I have two arrays $array1=('18753933','18753933','18771982') $array2=('18753933','18771982') My goal is to compare the values that are the same in both arrays. var countArticlesLoaded=0; for(var $i=0;$i ...

Receiving a Javascript Promise from a $.ajax request

Trying to convert a $.ajax() statement into an es6 Promise and return it as an es6 promise. The goal is to have an application layer with Create, Update, Delete calls to the Microsoft Dynamics Web API that return an es6 Promise for reuse across multiple pa ...

Error occurred during npm build with Browserify: Module not found

When I run npm build with the following command: "build": "browserify -t [ babelify --presets [ es2015 react ] ] app/assets/app.jsx -o public/javascripts/app.js" I encounter the error message below: Error: Cannot find module 'components/maininput.j ...

Error: Invalid Request - Nodejs Request Method

As part of my project involving payment gateway integration, I needed to make a call to the orders api. However, I encountered an error message: {"error":{"code":"BAD_REQUEST_ERROR","description":"Please provide your api key for authentication purposes."} ...

I'm getting errors from TypeScript when trying to use pnpm - what's going

I've been facing an issue while attempting to transition from yarn to pnpm. I haven't experimented with changing the hoisting settings yet, as I'd prefer not to do so if possible. The problem lies in my lack of understanding about why this m ...

Assistance with JavaScript regular expressions for dividing a string into days, hours, and minutes (accounting for plural or singular forms)

My challenge is with handling different variations in a string var str = "2 Days, 2 Hours 10 Minutes"; When I use : str.split(/Days/); The result is: ["2 ", ", 2 Hours 10 Minutes"] This method seems useful to extract values like "days", "hours" and " ...