WP-API / node-wpapi

An isomorphic JavaScript client for the WordPress REST API
http://wp-api.org/node-wpapi/
MIT License
1.68k stars 191 forks source link

then() not being called untill after a second call using electronJS #483

Open GRhin opened 3 years ago

GRhin commented 3 years ago

I hope I am not being an idiot here. I have just started playing around with this project using electronjs, and i have a basic issue where every call to wp does not respond untill i send another call to wp

var WPAPI = require( 'wpapi' );
var blah = ''
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var apiRootJSON = require( './SHCLobbyRESTAPI.json' );
var wp = new WPAPI({
    endpoint: 'http://localhost/SHCLobby/wp-json',
    routes: apiRootJSON.routes
});
function getLobbies(){
    wp.lobbies().get().then(function( response ) {
        console.log( response );
        blah = response;
    });
}

Thats the webpage js code. I then open my console and type "getLobbies()", and get nothing, blah is still "". After waiting for ages, and still nothing, I type "getLobbies()" again, and immediately get a console response, and blah is set. With a breakpoint in the then() function, it does not trigger untill the second call. After further experimentation, i can get it to run by calling "wp.lobbies().get()" and then the previous getLobbies() then function gets called. image

Any ideas on why this is happening? Id obviously prefer for the then function to be called immediately.

GRhin commented 3 years ago

If anyone comes accross the same issue, i got it to work by moving the "then" function into its own function.

function getLobbies(){
    wp.lobbies().get().then(recieveLobbies);
}
function recieveLobbies(response){
    console.log( response );
        blah = response;
}
GRhin commented 3 years ago

Well now that doesnt work, not sure what changed, havent really worked on it since i got it working. so to reiterate the issue:

wp.lobbies().get().then(recieveLobbies);
function recieveLobbies(response){
    console.log( response );
        blah = response;
}

this works as expected

function getLobbies(){
    wp.lobbies().get().then(recieveLobbies);
}
function recieveLobbies(response){
    console.log( response );
        blah = response;
}
getLobbies();

This does not work, the response is not recieved untill the second time the wp-api is called.

The temporary fix I am using is this:

function getLobbies(){
    wp.lobbies().get().then(recieveLobbies);
    wp.lobbies().get(); //this should not be needed, but forces previous line to get response.
}

function recieveLobbies(response){
    console.log( response );
        blah = response;
}