简体   繁体   中英

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

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.

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

You can simply await for your fetch request and assign it to a variable:

 const res = await fetch("fileName").then((response) => response.json()); console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM