Callback function in Moongose - javascript

is there anyway to return a value in a function with a callback function?
function getnextseq(){
autoincrement.findOneAndUpdate({ _id:"userid"}, { $inc: { seq:1}},function(err,data){
console.log(data.seq)
})
return data.seq;
}
console.log(getnextseq());

Simply return data.seq won't work since findOneAndUpdate is asynchrouse. You need either pass a callback function or use promise
function getnextseq(cb) {
autoincrement.findOneAndUpdate({ _id:"userid"}, { $inc: { seq:1}},function(err,data){
cb(data.seq);
})
}
getnextseq(function(seq) {
console.log(seq);
}
);
Or promise way
function getnextseq() {
return autoincrement.findOneAndUpdate({ _id:"userid"}, { $inc: { seq:1}}).exec();
}
getnextseq().then(function(seq) {
console.log(seq)
});

Related

Could you help me understand the sequence of execution?

doA(function(){
doB();
doC(function() {
doD();
})
doE();
});
doF();
excution order
doA() -> doF() -> doB() -> doC() -> doE() -> doD()
I don't understand why the execution order is as above...:(
The order the functions are executed depends on how doA and doC call their respective callbacks
Synchronously
function doA(cb) { console.log('doA'); cb(); }
function doB() { console.log('doB'); }
function doC(cb) { console.log('doC'); cb(); }
function doD() { console.log('doD'); }
function doE() { console.log('doE'); }
function doF(cb) { console.log('doF');}
doA(function(){
doB();
doC(function() {
doD();
})
doE();
});
doF();
or Asynchronously
function doA(cb) { console.log('doA'); setTimeout(cb); }
function doB() { console.log('doB'); }
function doC(cb) { console.log('doC'); setTimeout(cb); }
function doD() { console.log('doD'); }
function doE() { console.log('doE'); }
function doF(cb) { console.log('doF');}
doA(function(){
doB();
doC(function() {
doD();
})
doE();
});
doF();

How to return the value of SweetAlert2 input?

This is the current code I have
function getInput() {
Swal.fire({
input: "text",
}).then((result) => {
if (result) {
return(result.value);
});
}
function main() {
if (condition) {
const test = getInput();
} else {
// do something else
}
}
I know this isn't correct because it returns undefined. I've tried looking for a bunch of solutions but I always get undefined or the promise itself returned, have no idea how I'm supposed to get the value.
What I want to do is somehow return the value of the SweetAlert2 input so that I can use it in other functions.
Edit
I think I got mostly what I had wanted to do. Instead of putting the then handler in getInput(), I put it on test, so then I could put the rest of my code in the handler.
function getInput() {
return Swal.fire({
input: "text",
})
}
function main() {
if (condition) {
const test = getInput();
test.then((result) => {
if (result) {
// do stuff
}
});
} else {
// do something else
}
}
Ideal use case to use a callback as your program is not certain when the value will be returned.
In then handler, callback function will be invoked and input will be passed as an argument.
function getInput(cb) {
Swal.fire({
input: "text",
}).then((result) => {
if (result) {
return cb(result.value);
});
}
}
function main(input) {
console.log(input);
}
getInput(main)

How to refetch / update result in vue apollo query that used in a method

I want to update or refetch data in apollo query that used in a method (not apollo object). the thing is i wanted to query and update that query after specific event, so i couldn't use apollo object directly in in my code.
methods: {
async fetchEvents() {
const { data } = await this.$apollo.query({
query: gql`
query(
$someThing: Int,
) {
events (
someThing: $someThing,
) {
total
items {
...
}
}
}
`,
variables() {
return {
...
};
},
});
this.data = data;
},
},
watch: {
'items.view.organizerId': function callback() {
this.fetchEvents();
},
eventsSearchInputVal: function callback() {
this.fetchEvents();
},
'pagination.statusFilter': function callback() {
this.fetchEvents();
},
},
in conclusion when pagination.statusFilter or eventsSearchInputVal or items.view.organizerId in watch got changed the query should refetch. in this code nothing happen when those variables get changed.
i don't know why but I've changed variables() method to an object and it got fixed.
so this code is now working:
methods: {
async fetchEvents() {
const { data } = await this.$apollo.query({
query: gql`
query(
$someThing: Int,
) {
events (
someThing: $someThing,
) {
total
items {
...
}
}
}
`,
variables: { // this is an object now
...
},
});
this.data = data;
},
},
watch: {
'items.view.organizerId': function callback() {
this.fetchEvents();
},
eventsSearchInputVal: function callback() {
this.fetchEvents();
},
'pagination.statusFilter': function callback() {
this.fetchEvents();
},
},

Jasmine - How to chain a `.then` and a `.finally` in a callFake spy?

I have the following function, that does a service call with a promise and a .finally:
myService.getStuff().then(function() {
this.doStuffWhenServiceOK();
}, function () {
this.doStuffWhenServiceFails();
}).finally(function() {
this.doFinally();
});
I am spying on this service with the following spy:
spyOn(myService, 'getStuff').and.callFake(function() {
return {
then: function (succesFn, errorFn) {
return succesFn();
}
};
});
The problem is that the test complains that the .finally is not known. Just adding it after .then does not seem to be a solution...
return {
then: function(successFn) {
return successFn();
},
finally: function(successFn) {
return successFn();
}
}
Who knows how to chain .then and .finally in the callFake spy?
I work with Angular 1.
Return a finally function.
function then(succesFn, errorFn) {
succesFn();
return {finally:function() {}};
}

Order function call

I need to make submitAdapterAuthentication() function to work the first getUserRoles() function, but with the current implementation of the getUserRoles() function is being executed first that submitAdapterAuthentication(). How can I fix this?
checkOnline().then(function(onl) {
userObj.isLoginOnline = onl;
}).then(function() {
submitAdapterAuthentication(user, pass);
}).then(function() {
getUserRoles();
});
function submitAdapterAuthentication(user, pass) {
var invocationData = {
parameters : [ user, pass ],
adapter : "adapterAuth",
procedure : "submitLogin"
};
ch.submitAdapterAuthentication(invocationData, {
onFailure : function(error) {
WL.Logger.log("ERROR ON FAIL: ", error);
},
onSuccess : function() {
WL.Client.updateUserInfo({
onSuccess : function() {
//return promise
WL.Client.updateUserInfo({
onSuccess : function() {
}
});
}
});
}
});
}
// my function to obtain roles
// It should be performed after submitAdapterAuthentication
function getUserRoles(){
var arrayRoles = [];
var attributes = WL.Client.getUserInfo(realm, "attributes");
if(attributes){
if(attributes.roles){
arrayRoles.push(attributes.roles);
}
}
}
When chaining promises, if you return anything but another promise from a then() callback, the resulting promise will be resolved immediately with the value undefined.
In order to make sure your callbacks are executed in the order you specified, just make sure each callback is returning a promise at the end. If you want to return some value from a callback, wrap it in a $q.when(). In this case it looks like you are not using any intermediary return values, so you can just wrap any arbitrary value in a $q.when() to make sure a promise is returned:
checkOnline().then(function(onl) {
userObj.isLoginOnline = onl;
return $q.when(true);
}).then(function() {
submitAdapterAuthentication(user, pass);
return $q.when(true);
}).then(function() {getUserRoles();});
Based on your latest edit, it looks like ch.submitAdapterAuthentication() is likely returning a promise. If this is the case, you should return this promise from the function:
return ch.submitAdapterAuthentication(invocationData, {...
And then return this promise in the then callback:
then(function() {return submitAdapterAuthentication(user, pass);})
If ch.submitAdapterAuthentication() does not return a $q promise, you will have to wrap it yourself:
var deferred = $q.defer();
ch.submitAdapterAuthentication(invocationData, {
onFailure : function(error) {
WL.Logger.log("ERROR ON FAIL: ", error);
deferred.reject(error);
},
onSuccess : function() {
WL.Client.updateUserInfo({
onSuccess : function() {
deferred.resolve();
}
});
}
});
return deferred.promise;

Categories