JavaScript获取延迟



我有一个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;

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()回调之一,或者使用confirm()的非阻塞替代方案,如注释中所建议的。

最新更新