MarkLogic NodeJS JavaScript function return [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Like a person asked here (but his solutions as to call a nother function) https://stackoverflow.com/a/10796326/315200 ...I would like to know if its possible to have a function which doesn't call a second function on response of an async request, but simply return when the async request responses.
Something like this maybe:
function callToFacebook() {
var fbResponse;
FB.api('/me', function (response) {
fbResponse = response;
});
return fbResponse; //Will return undefined because CallToFacebook is async
}
Isn't that possible some way, without calling another function??
What I'm trying to achieve is to have one function I can call with some parameters, which will return the response object from a async webservice, like FB.

In short, no. You cannot have an asynchronous function return a meaningful value synchronously, because that value does not exist at that time (as it is built asynchronously in the background).
You can, however, return a Promise object, representing the "potential return value" of the asynchronous operation, and bind a function to that object using done() or similar. That way, your function gets return semantics (instead of having to chain the control flow into a callback), and remains asynchronous.

No, it's not possible.
You can't return value that is returned from async operation.
Think about it, you tell 10 people to have one mile running contest, they start now, will finish in one minute +-, but you want to know the answer now, it's not possible unless you're cheating...

Related

Node.js - prevent async await chaining [duplicate]

This question already has answers here:
How can I access the value of a promise?
(14 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am working with node.js and making calls to redis to get some values back. Making this call is async, where I use the await keyword. Like so:
async function getRedisValue(key) {
// does some stuff with the key here...
return await redis.getAsync(key)
}
Note how this uses the async keyword to allow the await. The issue I have is that by doing this, the next time I call this function, I need to use await (or .then()) again because async functions return a promise.
Eventually, this chained calls of await reaches a function in the jsonpath npm package, within the .apply function. Like:
jp.apply(data, path, (key) => {
// I need to return the values from redis here::
return getRedisValue(key);
})
Obviously here, the value returned is a pending promise. If I make that callback async and use the await - I still get a pending promise because the .apply function does not support async .
My question is, can I somehow stop the promise being chained up its hierarchy of calls? some how make getRedisValue not return a promise, but still wait for the redis call to be completed?
Or in general how to handle scenarios like this where I get stuck with nested await's?
Thanks.

How to return value from .then in promise to parent function/scope in JavaScript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
Ok, so I'm trying to modify a piece of existing code in a function I'm working on to integrate a database call to check for information stored there instead of just locally as is currently default in the library (commando.js).
The problem is, the database call is handled through a promise with sequelize. I need to return values from the .then() somehow to the parent function/scope? I know you can do this with async/await but because the function is part of a class that extends one from the library, it can't be an async function. Is there a way to return the value from .then() to the parent scope or is that simply not possible?
I've tried to use callbacks and they get the value back out to the parent scope but the function finishes executing before the callback returns so I don't think that'll work unless there's a way to wait for the callback to return?
Here's what I currently have:
nonAsyncFunction(args){
// Do stuff
database.getData()
.then((result)=>{
// Do Stuff
return value
});
return value // Need to somehow return value from .then() here?
}
If you have any questions or need any info from me feel free to let me know, otherwise thanks so much in advance for the help.
By design, this is not possible. You cannot synchronously wait for the resolution of a Promise, so you can't return the value a Promise resolves to.
This is because, for example, <script> elements in HTML without the defer attribute block parsing and rendering. It would be really bad if someone made made a synchronous HTTP request in them. That's why synchronous XHR on the main thread was deprecated.

Return result of nested promise success function (Javascript) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am building a wrapper function to retrieve values stored in a WebExtension's local Storage. I am struggeling to pass the return value of the success function to its outer function. Many thanks in advance!
get(key) {
browser.storage.local.get(key).then(onGot, onError);
function onGot(storage) {
console.log(storage[key]); // Works so far
}
function onError() {
return false;
}
// How can I return storage[key] here?
}
Either return a promise from the wrapper or let your promise resolve and consume the result with a callback.
A promise represents an operation which may or may not have completed yet. It provides hooks for success and failure so that the result of the async operation can be processed.
In order to return from the function, the caller and the executing function should stay in sync (w.r.t control flow). This moves away from async, which is what js promise is for.

Assing variable from inner callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
In my honest opinion this question is not duplicated because I know how to fix it using a callback as explain in the linked question, this question is specific about a situation where I cannot modify the outfer function and this is not covered in the another question
I use a library that I cannot modify, the library do something like this:
var result = Foo()
Then it uses result for the work. I can not modify how result works, I can only modify Foo because I pass it as parameter to the library.
If foo has something like this
funcion Foo(){
return "Hello"
}
It works perfect. Result is Hello and it works.
The issue is that my Foo has an async call inside it. It calls a web server and then it should return the response of the server. So
funcion Foo(){
request.get('http://server.com', function(error, response, body){
var parsed = JSON.parse(body);
return parsed.Hello;
});
}
In this case when var result = Foo();, result does not contains the response of the server (because is async) and continue with an empty result.
So if I only can modify Foo what should I do?
Update: If you dont find it possible I would love to hear alternatives like what should I ask in PR for the library, or a way to force the request to be syncronous
This is how you can work with a synchronous request:
funcion Foo(){
var request = new XMLHttpRequest();
request.open("GET", "http://server.com", false);
request.send();
function handleResponse(response) {
console.log(response);
}
handleResponse(request.responseText);
}
If you can only modify Foo, then modify it to send the request synchronously.
What you're trying to do is impossible per se, once code is asynchronous, it can't be used as you would synchronous code. That's why callback hell is a thing.
You could try to analyze the module internals and monkey patch it, but that may not be possible depending on what exports the module exposes.

Get content from .json and write to variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
What is the best way to just grab the content of a .json and store it to a var ?
I've seen some threads but i just can't manage on my code...
function retrieve_json() {
var content;
$.when(
$.getJSON("http://localhost/browsergame/data/test.json", function(data) {
content = data;
})
).then(function () {
console.log(content);
return content;
});
}
var json_content = retrieve_json();
console.log (json_content);
the console.log within the function displays the correct content of the json, the console.log at the very end of my code shows 'undefined'. I guess the async is the main issue here. I have tried doing it with $.ajax but couldn't manage either.
So, what is the best way to just grab the content of a .json file and store it to a var ?
The problem is that retrieve_json wont stop and wait until the json arrives from the server. The execution continues with whatever is after the statement starting with your $.when. In this case it's the end of the function. Since there is no return statement here, the function returns with the value 'undefined', what you store in json_content.
If you want to stop execution until the answer returns you have to wrap the next steps into a function and for example call it in the 'then' method of your example or just pass it to the getJSON where you store it in the content variable now.
And make sure you read up on how promises work.
Once code is async, it can't be made synchronous. You can only reliably use the content of your JSON in functions that you pass to promises or as callbacks, otherwise you have no guarantee that your JSON has been fetched when your code gets executed.
If you find even the promises syntax horrible you might be interested in async/await, a proposed syntax for ES7 that can be transpiled to ES5 right now with Babel.
Here's a good article which demonstrates the different approaches to asynchronous programming in JavaScript: The long road to Async/Await in JavaScript.

Categories