This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
This question may have been asked here before, and I'm sorry, but I wasn't able to find a solution to my problem anywhere. I am relatively new to JavaScript and things like "promises" are alien to me. I am trying to make a code that will load an array from a .JSON file, and after it loads, the code will continue.
async function fetchTags() {
var response = await fetch('../json/tags.json');
var json = await response.json();
console.log(json); // returns: Array()
return json;
}
function mainFunction() {
let tags = fetchTags();
console.log(tags); // returns: Promise { <state>: "pending" }
}
This is what my current code looks like, using a not-working "solution" I found on the internet. While the console.log(json), which is inside of the async function, returns the array correctly, the main function's console.log(tags) displays this promise with a "pending" state - and displays sooner than the array can be loaded, if I understand correctly.
The following code of the mainFunction() however relies strongly on this array, and it should not proceed before the array is loaded. Where am I making a mistake?
Thanks a lot for all your replies.
At this point, fetchTags is an asynchronous function and needs to be treated as such when calling it. You have two implementation options here:
Use async/await for your mainFunction function:
async function mainFunction() {
let tags = await fetchTags()
console.log(tags)
}
Appropriately handle the promise that is returned by the function:
function mainFunction() {
fetchTags()
.then(console.log)
.catch(console.error)
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed last year.
First Post, so forgive me for any general practices that I haven't followed.
Also very new to Chrome extension and Javascript so apologies for my noob question
I have the following code but getting the console is say undefined
function getFromStorage(key) {
chrome.storage.sync.get(key, function (r) {
const returnVal = r[key]
console.log(returnVal)
return returnVal
})
}
chrome.contextMenus.onClicked.addListener((selectionText) => {
var Val = getFromStorage("value")
console.log(Val)
});
But when I run the chrome.storage.sync.get in the listener, it works fine.
I have a few values from storage that I want to grab so thought a function would be better.
btw, using Manifest V3
Thank you in advance
The problem is that your getFromStorage doesn't return anything. It just calls an asynchronous API, then the callback runs and returns a value into the internals of the chrome API, which simply ignores this value.
Since chrome.storage returns a Promise in modern Chrome you can just await it directly.
Note that the function should be declared as async to allow using await inside.
async function getFromStorage(key) {
return (await chrome.storage.sync.get(key))[key];
}
chrome.contextMenus.onClicked.addListener(async info => {
let Val = await getFromStorage('value');
console.log(Val);
});
This question already has answers here:
How to return many Promises and wait for them all before doing other stuff
(6 answers)
Using async/await with a forEach loop
(33 answers)
Closed 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Okay, so I have this function that is a simple Axios request. We know that Axios will run as a promise based request so we do something like this and push all the responses into an array
let array = []
function A() {
return axios.get(url).then(r => r.data).then(r => array.push(r.forms))
}
The issue is now I need to call this function specifically 898 times.
async function main() {
await someArrayWithALotOfObjects.forEach(async (e) => {
return await A(e.url);
});
console.log(array);
}
The issue is when I run main() it console logs [], however when I change the main function to be completely hardcoded it outputs all the data correctly pushed to the array in a workable format.
async function main() {
await A(someArrayWithALotOfObjects[0].url);
await A(someArrayWithALotOfObjects[1].url);
await A(someArrayWithALotOfObjects[2].url);
await A(someArrayWithALotOfObjects[3].url);
await A(someArrayWithALotOfObjects[4].url);
await A(someArrayWithALotOfObjects[5].url);
await A(someArrayWithALotOfObjects[6].url);
await A(someArrayWithALotOfObjects[7].url);
...
console.log(array);
}
So my question is how to not hardcode because the loop does not seem to be completed before I run the console.log function.
Note: eventually I will be changing the console logging to the fs event for writing to a file if this helps in writing a better solution.
Note2: IDK how to use the new yield stuff in JavaScript yet, so if that is the solution needed forgive me.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I got some problems, to getting my code to do as i want.
I want to loop through all my newly created object from the movieList array, once the outer "getJSON" is done. But i can see that the array is empty when i loop through it.
Is there anyway to get this solution to work?
var url = "https://api.themoviedb.org/3/movie/popular?api_key=2c2a6a5ed606126f48db4cdbca91c0f0&language=en-US&page=1";
var genreUrl = "https://api.themoviedb.org/3/genre/movie/list?api_key=2c2a6a5ed606126f48db4cdbca91c0f0&language=en-US";
$.getJSON(url).then(function(movies){
var movieList = [];
movies.results.forEach(function(movie){
/* Get the genere names for single movie */
$.getJSON(genreUrl).then(function(genresHolder){
var genreNames = [];
//Pushes some info to the array
return genreNames;
}).then(function(genres){
movieList.push(new Movie(movie.id,movie.original_title,genres,movie.poster_path,movie.vote_count,movie.vote_average,movie.release_date));
})
counter++;
})
return movieList;
}).then(function (movieList){
movieList.forEach(function(movie){
//Appending each movie to html page
})
}).catch(function(err){
console.log(err)
})
Well, without more specifications in what getJSON is doing, it is difficult to say. But uour code should work. BUT most probably you are resolving getJSON without giving back the result from the url.
In a promise you can simply resolve() or resolve(value), whatever is passed in the call will go to the then(...) function.
I cannot see other obvious error, in this async calls then will be called ONLY after the promise is resolves.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm trying to understand promises better and have implemented code that basically looks like this:
console.log(getRemoteData())
function getRemoteData (){
return fetch('http://w.x.y.z')
.then(response => {
return response.json();
});
}
Assuming that getRemoteData() returns a promise, how do I access the value of that response? I've tried to resolve the promise before logging to the console and I can't get it to do anything but log the promise obj. I think I'm missing a fundamental component of how promises work.
I've tried searching SO and all the answers I find point to a //do something with the returned data comment in the .then() method but I'd like to learn what I should do from there. The returned value is an array[].
fetch(...) returns a promise, and response.json() returns another promise.
The returned value is not an array but a promise of an array. It should be:
getRemoteData().then(result => {
console.log(result);
});
The structure can be flattened similarly to synchronous code in async functions (ES2017). They are syntactic sugar for promises, this snippet is equal to the previous one:
(async () => {
const result = await getRemoteData();
console.log(result);
})();
Or use co if you are still on ES2015
var co = require('co');
co(function *(){
// yield any promise
var result = yield getRemoteData();
}).catch(onerror);
This question already has answers here:
jQuery deferreds and promises - .then() vs .done()
(11 answers)
Closed 7 years ago.
There is not much answer for this simple question that I have. My main question is that I have seen the .then method used a lot in JavaScript and I know the main thing where randomobject.then(//This returns success, //this returns failure). But there are things that I don't get such as the code here:
var success = function (response) {
return response.data;
};
var error = function (errResponse) {
$log.error(errResponse.data.Message);
};
function getsomeData() {
var url = baseUrl + 'api/somedata';
return $http.get(url).then(success, error);
}
First off in that code I'm wondering how the var success knows what data it is getting and the same with error. It says response.data but what is response? It's probably the result of the http.get but that doesn't make much sense code wise. Also it seems that when I have a function for example.
getsomeData returns what it returns. Why doesn't it work if I do the ff:
var dataHolder = randomAngularService.getsomeData()
it returns an object that holds a data under $$state but somehow the .then makes it work if you do the ff:
randomAngularService.getsomeData().then(function (response) {
if(response != null) {
console.log('got the data');
$scope.meeData = response;
}
});
I thought the .then only takes two parameters? This is what's confusing me.
Also is the .then property a JavaScript method or a jQuery one?
It's used to replace (or provide an alternate way) the old callback mechanism with a cleaner way to handle asynchronous requests, instead of passing your callbacks as parameters, you can chain your function with .then, given function will be executed once the promise gets resolved.
Anyhow, this is just a basic explanation, you should really get into the books of promises for more info.
I'm lazy to explain the whole promise thing, but just to answer question about .then
The 2 arguments inside .then actually means "call this function when the promise is resolved(success)/rejected(failed)"
About the arguments inside the functions, they should be specified in the API, because the caller (for instance $http.get) get to decide what to pass when calling that function.