How do I access data outside of the then scope when resolving a promise? [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Noob question here. Can someone elaborate on why seriesData variable outside the then scope is still an empty object. Additionally, what's the appropriate way of accessing data outside of said scope?
fetchData is a method that returns an array of three objects when successfully resolved.
Obviously, the console.log inside the then scope prints the expected seriesData object with the resulting data from the resolved promise.
Here's the code.
import fetchData from './data';
const seriesData = {};
fetchData()
.then(res => {
seriesData.characters = res[0];
seriesData.locations = res[1];
seriesData.episodes = res[2];
console.log(seriesData);
})
.catch(error => console.error(error.message));
console.log(seriesData);

Related

Why is createReadStream not updating a variable? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 months ago.
I am using fs.createReadStream to read CSV data and it is exhibiting some weird behaviour. I'm very confused as to why this is happening.
I have the following code:
const result = []
fs.createReadStream("path")
.pipe(csv()) //csv parser
.on("data", data => result.push(data))
.on("close", () => console.log(results)) // Showing results correctly here, 5000 rows
console.log(results) // Showing an empty array here []
I don't understand why the results array is going back to empty after the data was added correctly on close.

Javascript: how to save fetched data into a variable [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
How to save fetched data into variable in javascript
const SWAPI_URL = "https://random-word-api.herokuapp.com/word?number=10";
let darth = [];
fetch(SWAPI_URL)
.then(response => response.json())
.then(darthVaderObj => {
darthVaderObj
darth.push(darthVaderObj);
})
console.log(darth)
The console.log statement is executed before the saving in .then. That's why you will get undefined. This is the expected behavior of asynchronous programming.
Basically, you need to do everything in the .then function in order to have the resolved value of the fetch.

Javascript/Node.js - How to assign the output from a node-fetch to a var (Node-Fetch API) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I am writing some code for a program, but I'm not able to figure out how to assign the output of a fetch to a variable. Here's my code:
const fetch = require('node-fetch');
var totalNumOfPages;
fetch('https://api.hypixel.net/skyblock/auctions')
.then(res => res.json())
.then(totalPages => totalNumOfPages = totalPages)
console.log(totalNumOfPages)
The output is undefined, rather than the value of "totalPages" taken from the api. How can I assign the value of totalPages to the var totalNumOfPages.

Undefined global variable when returning data generated in a nested function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I have a function that I call which hits an API and returns a JSON, which I am calling getData. Inside that function is a nested function that processes the JSON and saves it to a new variable processedData when it's done making the request from the API.
I'd then like to return that processed JSON, but the console is telling me it's undefined. I didn't declare the variable so it should be treated as global. Why am I still having this issue?
The code won't work with the snippet because the API is only local, but processedData essentially looks like this: {'A': '123'}
function hitAPI() {
var getData = $.get('http://127.0.0.1:5000/myroute');
getData.done(function() {
processedData = (JSON.parse(getData['responseJSON']['data']));
});
return processedData;
};
var x = hitAPI()
console.log(x);

How to handle returning an inner callback variable? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
How do I access a variable inside a callback without reassigning it to a variable first?
For example, the following code works:
let volume = 0;
loudness.getVolume((err, vol) => {
volume = vol;
});
But what if I wanted it to be assignable directly to a const. The following returns undefined:
const volume = loudness.getVolume((err, vol) => vol));
The short answer is you can not. The callback function exists in it's own scope isolated from the rest of the code. The only way to extract that info to be used in the rest of the code is to assign it to a variable that exists in a parent scope.
In simple terms do what you did in your first example.

Categories