editor preopen event does not return boolean from api call function
editor preopen event does not return boolean from api call function
editor.on('preOpen', function(e, mode, action) {
let flag;
function checkCookiePresent() {
try {
const response = fetch("permission.py",{
method: 'post',
body: JSON.stringify({"action": "check_cookie"}),
headers: {
'Content-Type': 'application/json'
}
})
const data = response.json()
console.log('api res', data)
return data
}catch (err) {
console.log(err)
}
}
checkCookiePresent().then(function(result) {
console.log('abc', result)
flag = result.data
console.log('has cookie', flag)
});
if(flag != true){
var url = "http://stackoverflow.com";
// $(location).attr('href', url);
console.log('in if')
return false
}
else{
console.log('in else')
return true
}
});
Replies
event handler calls api function after the execution of flag condition, so I am getting the flag undefined. @Alan
You've got async code in there. The event handler returns before the
checkCookiePresent()
Promise is fulfilled.Is there a synchronous version of the checkCookiePresent code you can use? I'm not sure why checking for a cookie would need to use promises?
Allan
what would be best way then to hit backend API and after the response will decide to return boolean for event handler.
You'd need to make the Ajax call and then decide if you want to trigger Editor to display or not - e.g.
The
preOpen
event is synchronous.Allan