Explore promise value in Debug Console - javascript

While debugging node process in vscode, I can write arbitrary expression to be evaluated in the Debug Console. But I don't know how to get value if I write expression that returns Promise. It would be handy for example to explore what is in database calling the model function that returns promise.
I tried
Format.all(context.engine).then(formats => console.log(formats))
But still getting only Promise object back and not the value to be resolved.

Related

"await" seems successfully extract all nested Promises, why?

I was interested in "await" behavior, so I ran this code
console.log(await Promise.resolve(Promise.resolve(Promise.resolve("hahaha"))));
in my browser console, the result is correct "hahaha". It seems there is a hidden loop in "await" till no Promise remains. I didn't find explanation from MDN. Anybody knows why? Thanks.
From the MDN documentation:
This function flattens nested layers of promise-like objects (e.g. a promise that fulfills to a promise that fulfills to something) into a single layer — a promise that fulfills to a non-thenable value.
"hahaha" is the non-thenable value that it fullfills to.

Using Angular Http.Get() synchronously

I have a very simple requirement:
I'm writing a authorization service for an Angular site (Angular 7 it makes a difference).
The service needs a "hasPermission" function which takes a user and a resource name. It makes an Http.Get() call to a backend to determine whether or not the user is authorized to access that resource. When, and ONLY WHEN, the data comes back from the Get() call, it returns true or false.
I have been searching the web for about a week trying to figure out how to do it. My problem is that the Http.Get() returns an observable AND THEN CONTINUES. Which means the function returns before it receives the data back on which to make a decision. The same thing if I use the Http.Get().toPromise() - the function continues as soon as the promise is created.
It seems like every "solution" I read is some variant of "return a promise" or "return an observable". But then it's analagous to "It's turtles all the way down" -in this case, it's promises (or observables) all the way up. At some point there needs to be a method that waits for and returns the data, not a promise of the data or an observable of the data.
I need some way to add a "waitForDone" after creation of the observable or promise and before the function returns its value, but from everything I can find, you can't do that in JavaScript because it's single-threaded.
Note, I can't, as some solutions have suggested, "Just put the code after the http.get(...) in a separate function and call it from success callback" because the code to be execute needs to return from this function.
And async/await doesn't do it, because async turns the whole function into a promise, so, even though the await may wait for the Get() to return the data, the function will still have gone on and returned to the caller before it had the data it needed.
It doesn't seem to me that this is an unusual requirement. While it's nice to be able to issue a request then go do something else while you wait for the data to come back, there have to be times when you MUST HAVE the data before you can do anything else.
Any help is appreciated.
You can use the async-await syntax: instead of
get(someArgs).subscribe(doStuff);
you could put async in the function declaration and then go as follows
const someVal = await get(someArgs).toPromise();
doStuff(someVal); // this line won't execute until get() has resolved the promise
But, fundamentally, it is turtles all the way down. It's syntactic sugar atop of the Promise recipe, and that's what it gets transpiled to (if you transpile it).

Get value of resolved Promise in sync

If we know that a Promise is definitely resolved, how can we access the value and if we can't, why not?
let a = Promise.resolve(123);
console.log(a.value); // ???
The following does not work- it prints "First, Last, 123"
console.log("First");
Promise.resolve(123).then(console.log);
console.log("Last");
I'm asking how to get the value of an already resolved Promise synchronously and if that's not possible, why not?
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.
Promises are always asynchronous in JS.
If you're confident that promise is going to resolve then you can access it with .then method.
a.then(function(value) {
console.log("First");
console.log(value);
console.log("Last");
// expected output: 123
});
Variable a will lookalike below if it is console.log
Promise {<resolved>: 123}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: 123
For error handling, you can error block as mentioned in MDN docs.
Promise.resolve(123).then(function(value) {
console.log(value);
}
Take a look on this

How do I resolve an infinite Javascript promise?

I'm using the Apollo GraphQL library, and at one point it returns a promise. I can see that it's a resolved promise when I inspect it in the console:
Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: Object}
__proto__
:
Promise
[[PromiseStatus]]
:
"resolved"
[[PromiseValue]]
:
Object
However, when I Promise.resolve(thatPromise) I get back ... the same promise. No matter how many times I resolve the promise, it keeps returning a promise, making it impossible to access the promise's value.
I know the value is in there (if I inspect [[PromiseValue]] it's a plain object with values) ... I just can't figure out how to get it out at the code level instead of in the browser console.
Has anyone ever run in to something like this, and if so were you able to figure out how to extract the value of such an infinitely resolving promise?
P.S. I did try:
thatPromise['[[PromiseValue]]'];
but it appears to be a special browser value that you can't access from the code.
P.P.S. Just realized it may or may not actually be a promise. I get it by calling response.clone().json(), so while it looks like a promise maybe it's just a clone of a promise, in which case that might explain why I can't resolve it. However, it doesn't explain how I can extract the value.
EDIT
I think there's weirdness going on here and I'm not reporting all of the relevant details. Will post more info as soon as I sort things out better (don't want to send anyone on a wild goose chase).
There's no reason for you to have to call Promise.resolve to get the value. Remember that Promises are asynchronous. You have to access it's value like this:
myPromise.then(value => {
console.log(value)
// do whatever you're going to do with value
};
You can read up more [here][1] on how Promises work.

How to access JSON Object.$$state.value?

Warning: I'm going to sound like I have no idea what I'm talking about here, because I kind of don't. I'm in the process of self-learning Javascript and AngularJS through a lot of trial and error coding.
I have some javascript code (hesitant to copy here because it's a mess) that returns an Object with the following structure:
What I want to save to a variable is the object corresponding to Object.$$state.value in the picture. This object has username, hash and salt, which are what I care about. I don't know what all the other stuff like $$state are or how they got there.
However, if I do this (let's call the main Object "whatIHave"):
var whatIWant = whatIHave.$$state.value;
this does not work. whatIWant is null.
Does anyone recognize what's going on here? What is $$state, how did it get there, and how can I extract the value I want?
So that is a promise. You need to do something like:
whatIHave.then(function(whatIWant) {
// Work here
});
I highly recommend you to research what a promise is (like this link)
If you're curious enough, about what is that $$state and what is that value, I will explain a bit:
The promises have a $$state and there angular saves all the callback functions you want to call in a pending array (all those function you registered with .then like I explained before).
It also have the status: resolved (1) and rejected (2)
Finally, when you resolve or reject the promise, the value you pass when doing that, is saved in value.
You're trying to cheat in here, because when you try to access that value, it could be not there yet (that is what async is all about).
So the idea is learning the basic of promises, learning how to work with them and then use your whatIHave correctly.

Categories

Resources