【问题标题】:JavaScript fetch is delayedJavaScript 获取延迟
【发布时间】:2022-01-23 13:13:59
【问题描述】:

我有一个 Express 服务器正在等待我的网站执行某些操作。当我的站点做某事时,应该在 Express 服务器上调用一个 shell 脚本。问题是:shell 脚本仅在“确认窗口”被接受或拒绝后运行。我希望获取尽快发生。我什至不需要从 Express 服务器获取任何东西,我只想向 Express 发出信号,让其尽快运行 shell 脚本。

我在网站上有这个代码:

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");
    }
});

我在后端有这段代码:

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;

【问题讨论】:

标签: javascript node.js express fetch


【解决方案1】:

confirm() 是阻塞的,你只有一个线程。这意味着confirm() 将为您的应用程序停止世界,阻止fetch() 做任何事情。

作为最简单的解决方法,您可以尝试延迟调用confirm() 的时刻。这将允许fetch() 发出请求。

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);
});

其他选项是将 confirm() 放入 fetch 的 .then() 回调之一中,或者按照 cmets 中的建议使用 confirm() 的非阻塞替代方案。

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2018-01-20
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多