如何制作一个 JavaScript 程序,以便一个 API 调用不会隐藏另一个 API 调用?



我有一个JavaScript API,但是这个API不让其他API被调用,或者在它运行的时候再次调用自己。具体来说,这个API涉及到睡眠一段时间,当它处于睡眠状态时,我希望其他API调用或相同的API调用也应该发生。

我已经为此创建了一个示例程序,它的行为类似。期待您的评论和建议,谢谢。
'use strict';
// importing required libraries
const sleep = require("sleep");
const express = require('express');
const app = express();
const port = 1234;
const server = require("http").createServer(app);
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// this is the function that just sleeps for 30 seconds and after that is resolves the output
// because of this function the API calls needs to wait till it is completed
const promisified = async function () {
console.log("Promisified started")
return new Promise((resolve, reject) => {
let count = 0
console.log("promisified hit")
while (true) {
console.log("Sleeping for 30 seconds. Try: ", count);
sleep.sleep(30);
if (count >= 1) {
console.log("Timeout breaking");
return resolve("Broke out");
}
count += 1;
}
})
}
// this is the function that is being called on the API hit, which internally calls promisified function
const justafunction = async function (req, res) {
console.log("Just a function api hit");
res.status(200).send("api hit")
promisified()
.then(data => {
console.log("This then is workd...",data);
})
.catch(err => {
console.log("Error is :", err);
});
let x = await promisified();
console.log("X is here...",x);
}
// this is the API that we will call
app.get("/test", justafunction);
server.listen(port, function () {
console.log(" Server Successfully Started ", port);
});

理想情况下,在python和c++中会打开一个线程来独立完成这项工作,但我没有JavaScript的内部工作太多。因此,任何关于这方面的评论都将是非常感谢的。

JavaScript是单线程的:事件循环管理器线程执行JavaScript代码,因此在被执行的JavaScript代码运行完成(即返回到事件循环)之前不能做任何其他事情。

JavaScript中没有sleep函数。要同步运行这个函数,调用

sleep.sleep();

必须记录进入时的时间,并进入一个轮询循环,该循环读取时间,直到系统时钟提前到足以返回为止。在此之前,函数继续循环而不返回事件循环并阻塞线程。

另一种使用asyncawait的方法是:

function sleep( msec) {
return new Promise(resolve=>setTimeout(resolve, msec));
}
// calling example
async function test() {
console.log("sleep for 3000 msec");
await sleep(3000);
console.log("sleep expired");
}
document.querySelector("button").addEventListener("click", test);
Sleep for 3 seconds: <button type = "button">ok</button>

请注意,返回承诺的睡眠版本必须在await操作符之后从JavaScript中的async函数调用,或者使用then处理程序将实现处理程序添加到它。它与await一起工作的关键是await操作符返回到事件循环,直到它的操作数承诺完成,允许其他代码在主线程中执行。

最新更新