editor preopen event does not return boolean from api call function

editor preopen event does not return boolean from api call function

shashankVshashankV Posts: 4Questions: 1Answers: 0
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

  • shashankVshashankV Posts: 4Questions: 1Answers: 0

    event handler calls api function after the execution of flag condition, so I am getting the flag undefined. @Alan

  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin

    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

  • shashankVshashankV Posts: 4Questions: 1Answers: 0
    edited September 2021

    what would be best way then to hit backend API and after the response will decide to return boolean for event handler.

  • allanallan Posts: 63,535Questions: 1Answers: 10,475 Site admin

    You'd need to make the Ajax call and then decide if you want to trigger Editor to display or not - e.g.

    $.ajax({
      url: '...',
      success: json => {
        if (json.show) {
          editor.create(); // or whatever editing action is required
        }
      }
    });
    

    The preOpen event is synchronous.

    Allan

Sign In or Register to comment.