JavaScript 获取延迟
JavaScript fetch is delayed
我有一个 Express 服务器正在等待我的网站执行某些操作。当我的站点执行某些操作时,应在 Express 服务器上调用 shell 脚本。问题是:shell脚本只有在“确认window”被接受或拒绝后才运行。我希望抓取尽快发生。我什至不需要从 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()
的非阻塞替代方案,如评论中所建议的。
我有一个 Express 服务器正在等待我的网站执行某些操作。当我的站点执行某些操作时,应在 Express 服务器上调用 shell 脚本。问题是:shell脚本只有在“确认window”被接受或拒绝后才运行。我希望抓取尽快发生。我什至不需要从 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()
的非阻塞替代方案,如评论中所建议的。