Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

316
Views
how to return values from JS .then function [using arrow function]

Unsure how to access the values date and prices else where in the script

fetch("fileName")
.then(response => response.json())
.then(data => {
    var date  = data.JSONdata[data.JSONdata.length - 1].date
    var prices = data.JSONdata[data.JSONdata.length - 1].prices
})
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can simply rewrite your code to use async/await:

const response = await fetch("fileName");
const data = await response.json();
const date  = data.JSONdata[data.JSONdata.length - 1].date;
const prices = data.JSONdata[data.JSONdata.length - 1].prices;

EDIT: To use this asynchronous code, you have to define the function in which you use this code as async:

async function yourFunction() {
    // your async code from above
}

// await async function where it's called
const functionResult = await yourFunction();

You have to make every function in your callstack async up to the level where you no longer care about the response. So the function which calls "yourFunction()" has to be async aswell. And so on.

about 4 years ago · Juan Pablo Isaza Report

0

You can use await to get the Promise result. Please refer MDN docs

In the given example date and prices are hard-coded which will be fetched via API calls in real-scenario

const date = Date.now();
const prices = [1000, 2000];
const resolvedProm = Promise.resolve({date, prices});

let thenProm = resolvedProm.then(({date, prices}) => {
    return {date, prices};
});

let res = await thenProm;
console.log(res); 
// {date: 1641136463085, prices: Array(2)}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!