Home > Mobile >  JavaScript fetch is delayed
JavaScript fetch is delayed

Time:12-22

I have an Express server waiting for my website to do something. When my site does something, a shell script should be called on the Express server. The problem is: The shell script is only run after the "confirm window" has been accepted or denied. I want the fetch to happen as soon as possible. I wouldn't even need to get anything from the Express server, I just want to signal Express to run the shell script as soon as possible.

I have this code on the website:

messaging.onMessage(function (payload){

    fetch("http://localhost:9000/testAPI")
        .then(res => res.text())
        .then(res => console.log("something:"   res));


    var r = confirm(callingname   " is calling.");
    if (r == true) {
        window.open(payload.data.contact_link, "_self");
    } else {
        console.log("didn't open");
    }
});

I have this code on the backend:

var express = require("express");
var router = express.Router();

router.get("/", function(req,res,next){
    const { exec } = require('child_process');
    exec('bash hi.sh',
        (error, stdout, stderr) => {
            console.log(stdout);
            console.log(stderr);
            if (error !== null) {
                console.log(`exec error: ${error}`);
            }
        });
    res.send("API is working");
});

module.exports = router;

CodePudding user response:

confirm() is blocking, and you only have a single thread. This means confirm() will stop the world for your application, preventing fetch() from doing anything.

As the simplest possible fix, you can try delaying the moment when confirm() is invoked. This would allow fetch() to get the request out.

messaging.onMessage(function (payload) {
    fetch("http://localhost:9000/testAPI")
        .then(res => res.text())
        .then(text => console.log("something:"   text));
    
    setTimeout(function () {
        if (confirm(`${callingname} is calling.`)) {
            window.open(payload.data.contact_link, "_self");
        } else {
            console.log("didnt open");
        }
    }, 50);
});

Other options would be to put confirm() into one of the .then() callbacks of fetch, or to use a non-blocking alternative to confirm(), as suggested in the comments.

CodePudding user response:

The JavaScript Fetch API is designed to provide a simple and easy way to fetch data from remote servers. It's a native JS alternative to Ajax. The idea is simple, just call a function that takes two parameters: the URL to the server you want to get the data from, and an object of options. For example, you can create a GET request like so: var xhr = new XMLHttpRequest(); xhr.open("GET", "http://www.example.com/some_data", true); xhr.send(); There is also a set of common options that we can pass into the function: xhr.withCredentials=true; xhr.responseType="json"; So, you've got the basics, now how do you actually send the request? The function returns a promise, so let's handle that first: // Get the data var promise = xhr.fetch("http ://www.example.com/some_data", { responseType: "json" }); // Wait for the data to load var response = await promise; // If we want to make sure that we are only using data from // the most recent request, then we need to make sure we're sending // the request again after we have loaded the data. We can do that // by using the request property of the promise object. var response = await promise.request(); Now, let's put it all together and make sure that it works: // Get the data var promise = xhr.fetch("http://www.example. com/some_data", { responseType: "json" }); // Wait for the data to load var response = await promise; // If we want to make sure that we are only using data from // the most recent request, then we need to make sure we're sending // the request again after we have loaded the data. We can do that // by using the request property of the promise object. var response = await promise.request(); console.log(response.json); // Show the result here. This will print out the JSON from // the server.

}

JavaScript Fetch API is Delayed

Read more here : https://macrotechhelp.blogspot.com/2021/12/fix-javascript-fetch-is-delayed.html

  • Related