Is it possible to get the original promisevalue without the 2nd then statement or am I accessing the promise incorrectly with the 2nd then statement.
You must use either .then()
or await
to get the data out of the promise. The data is retrieved asynchronously so the only wait to get it out of the promise is with .then()
or await
. And, if using await
, it would have to be inside an async
function.
While promises and async/await
are helpful for managing asynchronous operations, they cannot change the fact that the data is retrieved asynchronously and will not be available synchronously. So, you have to use asynchronous tools to get to the data. In this case, that's .then()
or await
.
And, to use await
, you have to be in an environment that supports it. Modern browsers do support it (and you're already using fetch()
which requires a semi-modern browser), but not some of the older browsers still in use by some so that is a consideration. In this case, you should probably use .then()
.
Also, note that in this coding structure:
json.then(function(getData){metaData = getData;});
where you're assigning the data from the promise to a higher scoped variable is nearly always a warning sign that you're attempting to use the data in a scope in which you don't know the timing for when the data is actually available and doing something wrong.
The ONLY scope that you can safely use the data is INSIDE the .then()
handler or in a function that you call from there and pass the data to. Don't assign it to a higher scope and then try to just blindly use in that higher scope. You won't have any idea when the data is actually valid. You only know that timing information inside the .then()
handler.
json.then(function(data){
// use the data here
// write the code in here that uses the data
// or call some function here that you pass the data to
processData(data);
});
// can't use the data here (it's not yet available)
For further explanation of this issue see: How do I return the response from an asynchronous call?