Promise inside a sync function never resolves - asynchronous

what happens when promise function inside asynchronous function never resolves or rejected ,so inside below save method if both initial if conditions get not satisfied what will happen, it's not giving error,will it wait there forever till response receive?
save().then(results=>{
})
save():promise<any>{
if (conditionA) {
return http request
}
if (conditonB) {
return http request}
}
}

If your promise sometimes returns a promise, then it should always return a promise. The usual design pattern if you find you don't need to have a promise to return in some code paths is that you just do a return Promise.resolve(). So, keep with your pseudo-code, you'd do something like this:
save().then(results=>{
})
save():promise<any>{
if (conditionA) {
return request(...);
} else if (conditonB) {
return request(...);
} else {
return Promise.resolve(...);
}
}
You fill in the ... parts above to make sense for your function. But, if you sometimes return a promise, then ALWAYS return a promise. Then, the caller can just consistently use the returned promise. If the work is already done (or there was nothing to do), then you just return an already resolved promise and the caller always gets a consistent return value which they can use as a promise.
Note, that none of this matches the title of your question, but it does fully match the body of your question. Is your title just wrong or is there some part of your question description that is missing?

A simple answer should be ,save() cannot be undefined if any kind of promise is returned from the method including the service call(http call),
if it never resolves it will never go into then part of the handler ,but it cannot give the error undefined.
undefined error can be given when no condition satisfied in the if else conditions and nothing returns.

Related

How does rust simply get a return from a closure

Here's the problem I'm having with tauri.
'return' shows you the return value I need, and I know for a fact that writing it this way does not work at all.
'pick_file' is called asynchronously, and I know that message passing seems to work, but is there an easier way to get the value I need.
#[tauri::command]
fn open_file() -> String {
dialog::FileDialogBuilder::default()
.add_filter("data", &["json"])
.pick_file(|path_buf| match path_buf {
Some(p) => return format!("{}", p.to_str().unwrap()),
_ => return "".into()
});
}
First, return in a closure returns from the closure and not from the function that contains it.
The more fundamental issue is that you can't return a String from open_file() if you use FileDialogBuilder::pick_file(). According to the documentation, pick_file() is non-blocking and returns immediately without waiting for the user to pick the file. What you can do in the closure is send the file down a channel, and pick it up elsewhere.

UnhandledPromiseRejectionWarning when using Fluture `encaseP` on `fetch`

I have just started using Flutures, and I am trying to fetch some remote data for a visualization with d3.
I created a function which accepts a DOM selector (e.g. #my-chart) and a url (e.g. https://example.com/data.json).
If an error occurs when fetching the data, I have a unary function that shows an error message. If everything goes well, I have a unary function that draws the visualization. For the sake of simplicity, let's suppose that these functions are just console.error and console.log.
const fn = async (selector, url) => {
// convert fetch (which returns a Promise) into a function that
returns a Future
const fetchf = Future.encaseP(fetch);
fetchf(url)
.chain(res => Future.tryP(_ => res.json()))
.fork(console.error, console.log);
}
Apparently I am missing something when wrapping fetch in a Future, because I get this warning:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
If I had to use async/await I would write something like this, which would not give me any warning.
const fn = async (selector, url) => {
let res;
try {
res = await fetch(url);
} catch (err) {
console.error(err);
return;
}
let data;
try {
data = res.json();
} catch (err) {
console.error(err);
return;
}
console.log(data);
};
It seems two things are going on here:
The data.json() function is not supposed to be wrapped inside tryP, because according to your second not broken example, it returns synchronously (there is no await). This would cause Fluture to raise a TypeError (because it expects to see a Promise, but gets a JSON value). Although, knowing the fetch API, data.json() typically does return a Promise, so it might also be your second example is broken, and something else is going on. Whatever it is, I suspect that an unexpected Error is being thrown somewhere. Do you see any other error messages in your console, besides the one you posted?
I did some testing, and it does seems to be true - when Fluture raises or catches a TypeError after a successful encaseP, it seems the original Promise manages to catch that error, and trigger the unhandled rejection. This appears to be a regression bug in Fluture, and I will be fixing it soon. In the meantime, if we get to the bottom of what's throwing your error, you will be able to continue without depending on said fix.
EDIT: I've opened a PR to fix the second issue: https://github.com/fluture-js/Fluture/pull/310
EDIT2: The fix has been released under version 10.3.1. Using that version should give you more insights in what's happening with issue 1.

A function to read data from FireBase but requires Unit instead

I've made a function that calls on the FireBase database and will return a MutableList. However, when I try to make it return on a specific line, it says it requires a Unit instead of the MutableList.
fun firebaseCollect(key: String): MutableList<CustomList> {
var ref = FirebaseDatabase.getInstance().getReference(key)
var lessonList = mutableListOf<CustomList>()
ref.addValueEventListener(object: ValueEventListener{
override fun onCancelled(p0: DatabaseError?) {
}
override fun onDataChange(p0: DataSnapshot?) {
if (p0!!.exists()) {
lessonList.clear()
for (index in p0.children) {
val lesson = index.getValue(CustomList::class.java)
lessonList.add(lesson!!)
}
return lessonList
}
}
})
return lessonList
}
Type mismatch. Required: Unit, Found: MutableList< CustomList > is found at the first return lessonList since what I am asking for it to return is a MutableList not a Unit. I am confused as to why this happens. The last return would give an empty list. It is currently my first jab at FireBase and this is a practice I am doing. The rules for read and write have been set to public as well. How should I recode the function that I am able to return the data from FireBase into the function and passed back to the caller?
Firebase APIs are asynchronous. For your case, that means addValueEventListener returns immediately. Then, some time later, the listener you passed to it will be invoked with the data you're looking for. Your return statement in the callback doesn't actually return any data to the caller. In fact, you can't return anything from that callback. At the bottom of your function, when you return lessonList, you're actually returning an initially empty list to the caller, which may change later when the data finally arrives.
To get a better sense of how your code works, put log lines in various places, and see for yourself the order in which the code is invoked. You can read more about why Firebase APIs are asynchronous by reading this article. The bottom line is that you'll need to interact with the asynchronous APIs using asynchronous programming techniques. Don't try to make them synchronous.
Data is loaded asynchronously from Firebase. Once the data is fetched the method onDatachange() is invoked.
You are returning lessonList inside onDatachange(). Return type of onDatachange() is void(Unit in kotlin). This is the reason for the type mismatch error.
For returning the result from the method onDatachange() try this.

Get reactive value from subscription in meteor

In Meteor, how do I properly return a value from a property (in this case response) from a collection so that I can send it to a data propert? I have tried the following function:
Responses: function(answer) {
return Responses.findOne({answerId: answer.hash.answer});
}
Which I call in the spacebars template as:
data-selected="{{Responses answer=_id}}
When I look at the HTML it says that the data-selected="[object object]" which is not super surprising but I can't figure out how to return just the response value from the match. I can add .response onto the end and it works but gives an expected 'undefined' error I know that it is not reactive. I have seen people use wrapasync but that was for methods, not subscriptions. I should note that there are several responses, so the code would have to be suitable inside a #for loop of answers which the responses variable is keeping track of the input from each user separately.
Thanks!
I'm not sure about data-selected="{{Responses answer=_id}}". Since you're already inside a for loop your html code can simply look like this:
data-selected="{{Responses}}"
Inside your helper function you can then say:
var myResponse = Responses.findOne({answerId: this._id}).response;
if (myResponse != null){
return myResponse;
else {
return "";
}
When the page is still loading and the data is not yet available, myResponse is still null, so the helper returns the empty string "". Shortly thereafter the data becomes available and your data gets returned, without any error in your console.

nodeJS waiting for function to return before continuing

Just having some issues with building a function using nodeJS. It doesn't seem to be returning the value, and I have a feeling its due to the asynchronous nature of the function call. Any help would be really appreciated!
sendFilesToDB is sent an array (from fs.readdir) of files to be processed. The files' content is used to construct a SQL query. Once successfully inserted, the file is deleted. But the fileToQuery function does not return a string at all (gives a 'Argument must be a string' error).
fileToQuery is returning void, because it says:
function fileToQuery(filePath) {
do_something(...);
}
That return statement you have isn't returning from filesToQuery but from the anonymous function you defined it in.
You need to rewrite your fileToQuery function to take an extra argument (perhaps resultCallback) and instead of returning your sql string, you do:
return resultCallback("INSERT IGNORE ....");
You'll then call it like this:
fileToQuery(file,function(query){
client.query(query, function(err, results) {
fs.unlink(file, function(err) {
sendFilesToDB(files);
});
});
});
By the way: This is called "continuation passing style" and can be done in any language that supports anonymous functions. What you asked for is called a callable continuation, but not very many languages have them. If you're interested in learning about them you should try picking up scheme.

Resources