How to access the value of a promise?
promiseA
's then
function returns a new promise (promiseB
) that is immediately resolved after promiseA
is resolved, its value is the value of the what is returned from the success function within promiseA
.
In this case promiseA
is resolved with a value - result
and then immediately resolves promiseB
with the value of result + 1
.
Accessing the value of promiseB
is done in the same way we accessed the result of promiseA
.
promiseB.then(function(result) {
// here you can use the result of promiseB
});
Edit December 2019: async
/await
is now standard in JS, which allows an alternative syntax to the approach described above. You can now write:
let result = await functionThatReturnsPromiseA();
result = result + 1;
Now there is no promiseB, because we've unwrapped the result from promiseA using await
, and you can work with it directly.
However, await
can only be used inside an async
function. So to zoom out slightly, the above would have to be contained like so:
async function doSomething() {
let result = await functionThatReturnsPromiseA();
return result + 1;
}
how to get the value from a Promise resolve?
Your convertFileToString
looks a little wrong: you should be invoking resolve()
in the onload
handler, not the other way round:
convertFileToString(file){
return new Promise((resolve, reject)=>{
let fileReader = new FileReader();
fileReader.readAsText(file);
fileReader.onload = (event) => {
resolve(event.target.result);
}
})
}
How to access values of a Promise?
How to extract data out of a Promise
NO you can't get the data synchronously out of a promise like you suggest in your example. The data must be used within a callback function. Alternatively in functional programming style the promise data could be map()ed over.
If your are OK using async/await (you should it's awesome) then you can write code that looks synchronous yet retain the asynchronicity of a promise (see @loganfsmyth comments).
const { foo, bar } = await iAmAPromise.then(result => result.data);
Overall since you are already using ES6 I assume you are also using a transpiler. In which case you should definitely give async/await a try.
Just be sure to weight in the decision that as today they are not yet a ratified specification.
Get value of resolved Promise in sync
No, it is not possible to do this. This is by design.
The Promise A+ specification is meant to be used as a simple, consistent way to deal with asynchronous operations. One of the constraints is that passing a new callback on to then()
on an already resolved promise will always execute on a later tick in the event loop, so things are consistent.
Adding a secondary way to inspect promise results would not have been impossible. It would probably have been quite easy to do so, but there's at least 2 problems with adding this to the specification:
- If you're looking to build a specification, you want it to be as simple as possible. The specification itself actually only defines the
then()
function. - By adding this feature, you're opening the door to hordes of developers getting even more confused about something that's already hard to grok.
Promises and asynchronous operations are hard for people to understand. I see questions here daily about promises and not 'getting' it. If non-async way to access promise results would be added to the default promise, I'd imagine that this would be an even larger amount. It's good to try and enforce 'the right way' of doing things.
However, this decision is not simply made for you. You're not stuck there. You can very easily build your own version of a promise that has this feature, and still works with existing promises. As long as your object has a then()
function that behaves according to Promises/A+ you can do with the rest of the object whatever you want.
Is there a way to save [[Promise Result]] as a variable?
There are 3 ways for solving this:
- Since you return a promise, use
.then
to get the returned value.
function currentloginid() {
return fetch('http://localhost/gaq/api/api.php?action=userid', {
method: 'GET',
})
.then(function(response) {
return response.json();
})
.then(function(data) {
var userid = JSON.parse(data);
console.log(userid);
return userid;
})
}
currentloginid().then(value => console.log(value));
Get the array value of a promise
Related Topics
Angular - How to Get Result of a Json Object
Scrollable Table With Fixed Headers and Fixed First Column
How to Trigger a Click Event on Disabled Elements
React Native: Image Not Displaying With Dynamic/Local Uri
Check If a String Is HTML or Not
Chrome Blank Pdf Print Preview
How to Stop Parsefloat() from Stripping Zeroes to Right of Decimal
Filter Json Object to String Array by Key Value
Push Objects into an Array in Reactjs
Detecting When User Scrolls to Bottom of Div With React Js
React-Native React-Navigation Undefined Is Not an Object (Evaluating 'S.Value.Startswith')
Angular Load Async Data Before Component Initialization
Change Specific Button Text on Click Inside Ngfor
Reactjs: Expected Onclick Listener to Be a Function, Instead Got Type String
Programmatically Clicking Button in React Native
Whenever I Click Outside the Element It Should Close
Javascript - How to Remove All Extra Spacing Between Words
How to Split Date and Time from the Datetime Variable in JavaScript