Why doesn't the callback function runs in this code? - callback

I've been trying to run the following code but only the second function runs and the first one does not execute. Can anyone please let me know what's wrong.
function first() {
setTimeout(function(){
console.log(1);
}, 500 );
};
function second(first) {
console.log(2);
};
second();
What I'm expecting is that the program first displays 1 after 500ms and then 2.

What you expect :
function first() {
setTimeout(function(){
console.log(1);
second();
}, 500 );
};
function second() {
console.log(2);
};
first();
Your 'first' parameter in the second function does nothing. Instead you can do this too :
function first(callback) {
setTimeout(function(){
console.log(1);
callback();
}, 500 );
};
function second() {
console.log(2);
};
first(second);

I think this is the effect you're trying to achieve. first accepts a callback function as a parameter. It then needs to be called somewhere inside of the first function.
function first(callback) {
setTimeout(function() {
console.log(1);
callback(); // Calling the passed function
}, 500);
};
function second() {
console.log(2);
};
first(second); // Passing the 'second' function as a callback

you just called second. you most call first for callback funtion for you expectation your code shoould be like this
function second() {
setTimeout(function(){
console.log(2);
}, 500 );
};
function first() {
console.log(1);
second();
};
first();

Related

how can you use oncanplaythrough after a setimeout?

i assume this doesn't work because canplaythrough is fired too early?
function splasher() {
showDelay = setTimeout(vidCheck, 6000);
};
function vidCheck() {
vid.addEventListener("canplaythrough", showPage);
};

SailsJS Installable Hook not executing the beforeCreate override

I tried adding an installable hook sails-hook-myoverride that looks like this:
let carryOn = (values, proceed, previous) => _.isFunction(previous) ? previous(values, proceed) : proceed();
module.exports = function (sails) {
return {
initialize: function (cb) {
sails.after(['hook:orm:loaded'], function () {
_.each(sails.models, (model) => {
let previousBeforeUpdate = model.beforeUpdate;
model.beforeUpdate = function (values, proceed) {
console.log("myoverride::beforeUpdate", values);
return carryOn(values, proceed, previousBeforeUpdate);
};
let previousBeforeCreate = model.beforeCreate;
model.beforeCreate = function (values, proceed) {
console.log("myoverride::beforeCreate", values);
return carryOn(values, proceed, previousBeforeCreate);
};
});
cb();
});
}
}
};
Then in my Test model I added both beforeUpdate and beforeCreate methods:
beforeUpdate: function (values, cb) {
console.log('Test::beforeUpdate');
cb();
},
beforeCreate: function (values, cb) {
console.log('Test::beforeCreate');
cb();
}
And then I called POST on http://localhost:1337/test to test it.
Surprisingly, sails printed only Test::beforeCreate and not myoverride::beforeCreate as well, as I was hoping it would.
Google did not help and neither did Sails documentation :(
I'm completely lost at the moment...
OK, apparently, using sails.after(['hook:sockets:loaded'], function () { works for some reason...

api request returns undefined

maybe is a stupid question but,
when I'm calling api from 'outside' function it always returns undefined,
for example:
actions.js
import axios from 'axios'
export function getProducts() {
axios.get('http://localhost:8000/api/products').then((response) => {
return response;
});
}
and then in a component:
mounted() {
this.products = getProducts();
console.log(this.products);
}
returns undefined
of course when I make a request from component it returns result
mounted() {
axios.get('http://localhost:8000/api/products').then((response) => {
this.products = response;
console.log(this.products);
});
}
Why is this happening and how can I solve this problem?
Thanks
You are returning the response value in the then callback of the axios.get call. However, your getProducts function doesn't return anything.
Simply return the axios.get call:
export function getProducts() {
return axios.get('http://localhost:8000/api/products');
}
Then, the result of getProducts will be the Promise returned by axios.get(). So, you can add a then callback on the result of getProducts and set you this.products that way:
mounted() {
getProducts().then(products => this.products = products);
}

How to access other function in UI5 custom control/type?

I defined many custom type in Utils.js: http://plnkr.co/edit/BGqDoWEC7DTmomEFHygd?p=catalogue
I want to add trim() in parseValue
parseValue: function (oValue) {
if(oValue !== null) {
return oValue.trim();
}
return oValue;
},
Copy and paste this function is kind of dumb, so I want to do sth. like :
trimString : function(oValue) {
if(oValue !== null) {
return oValue.trim();
}
return oValue;
},
mandatoryValueType : SimpleType.extend("text", {
formatValue: function (oValue) {
return oValue;
},
parseValue: this.trimString,
validateValue: function (oValue) {
if (!oValue) {
throw new ValidateException(Utils.i18n("MANDATORY_VALIDATE_ERROR"));
}
}
}),
But scope in mandatoryValueType seems can not access to this.trimString, what can I do?
this scope in parseValue function, no trimString function:
Another working sample : http://plnkr.co/edit/ahS6NlUHHL0kdvdddvgd?p=preview
Reference: https://sapui5.hana.ondemand.com/#/sample/sap.m.sample.InputChecked/preview
Maybe you can put the trimString function outside the var Utils object, and set it as a global function.
here is the example: http://plnkr.co/edit/u64DEP0RnT5CJADZyXJg?p=catalogue
edit:
corrected by #boghyon, the trimString function should be a function in a closure, instead of a global function :)
in this case the this keyword contains the object which invokes the function: the controller which invokes mandatoryValueType of utils.js.
initialise in utils.js in the upper scope of mandatoryValueType a var that = this. then use inside of mandatoryValueType instead of this.trimString the that.trimString.
edit
self reference to a property of an object in a literal declaration of an object:
var Utils = {
...
trimString: function() {
...
},
...
parseValue: function() {
this.trimString();
}
..
}

for loop not waiting for function to end

I have 5 links on a page and i have to check if all are links are working or not. Here is the code
// iterate through each link and check if ti works.
for(var i=0; i < 5; i++) {
var ifLinkWorks = verifyLinkWorks(links[i]);
if(ifLinkWorks){ OK }
else{ error }
}
This is verifyLinkWorks function. It opens a link. After it get opened, it checks if the page is loaded properly
function verifyLinkWorks(link) {
return winjs.Promise(function(complete) {
link.click();
// wait for page to load
return winjs.promise.timeout(4000).then(function () {
// check if page is loaded
var islinkOK = IsPageLoaded();
complete(islinkOK); // i want verifyLinkWorks to return this value
});
});
}
After reaching link.click(), it is not waiting for page to load. Instead it jumps to the if condtion in outer for loop (which makes linkWorks = undefined therefore,gives Error). How to make it wait in the verfifyLinkWorks function.
Thanks in advance...
You'll need to wait for the results of each promise, either all at once, or individually. As the actions are all async in nature, the code can't wait, but it can call a function when it completes all of the work.
Here, I've created an array which will hold each Promise instance. Once the loop has completed, the code waits for all to complete, and then using the array that is passed, checking the result at each index.
// iterate through each link and check if it works.
var verifyPromises = [];
for(var i=0; i < 5; i++) {
verifyPromises.push(verifyLinkWorks(links[i]));
}
WinJS.Promise.join(verifyPromise).done(function(results) {
for(var i=0; i < 5; i++) {
var ifLinkWorks = results[i];
if (ifLinkWorks) { /* OK */ }
else { /* error */ }
}
});
In case the link.click() call fails, I've wrapped it in a try/catch block:
function verifyLinkWorks(link) {
return WinJS.Promise(function(complete, error) {
try {
link.click();
} catch (e) {
complete(false); // or call the error callback ...
}
// wait for page to load, just wait .. no need to return anything
WinJS.Promise.timeout(4000).then(function () {
// check if page is loaded
var islinkOK = IsPageLoaded();
// finally, call the outer promise callback, complete
complete(islinkOK);
});
});
}
If you want to check the validity of a URL, I'd suggest you consider using WinJS.xhr method to perform a HEAD request instead (rfc). With each link variable, you can use a timeout to validate that there's a reasonable response at the URL, without downloading the full page (or switch to a GET and check the response body).
WinJS.Promise.timeout(4000,
WinJS.xhr({
type: 'HEAD',
url: link
}).then(function complete(result) {
var headers = result.getAllResponseHeaders();
}, function error(err) {
if (err['name'] === 'Canceled') {
}
if (err.statusText) {
}
})
);
Ok heres the link to the msdn code sample for win js promise object.
Promise winjs
now going through the code
<button id="start">StartAsync</button>
<div id="result" style="background-color: blue"></div>
<script type="text/javascript">
WinJS.Application.onready = function (ev) {
document.getElementById("start").addEventListener("click", onClicked, false);
};
function onClicked() {
addAsync(3, 4).then(
function complete(res) {
document.getElementById("result").textContent = "Complete";
},
function error(res) {
document.getElementById("result").textContent = "Error";
},
function progress(res) {
document.getElementById("result").textContent = "Progress";
})
}
function addAsync(l, r) {
return new WinJS.Promise(function (comp, err, prog) {
setTimeout(function () {
try {
var sum = l + r;
var i;
for (i = 1; i < 100; i++) {
prog(i);
}
comp(sum);
}
catch (e) {
err(e);
}
}, 1000);
});
}
</script>
you will see the addAsync(3,4).then() function. So all the code is to be kept inside that function in order to have a delayed response . Sorry m using a tab so cannot write it properly.
Also go through link then for winjs promise