我正在开发一个带有节点JS的应用程序,该应用程序会生成一个调用端点的报告api.example.com/generate-report
但是这个报告大约需要1分钟生成,然后我想实现类似的东西:
这可以用nodejs吗?
答案 0 :(得分:0)
在我做了一些研究后,可以使用Promises轻松完成。
要运行以下代码,必须安装express和node uuid
npm install --save express
npm install --save uuid
node index.js
索引的源代码是:
//index.js
const express = require("express");
const app = express();
const PORT = process.env.PORT || 5000;
const uuidV1 = require('uuid/v1');
// this is where we'll store the results of our jobs by uuid once they're done
const JOBS = {};
app.get("/", (req, res) => {
res.send("It works!");
});
app.get("/startjob", (req, res) => {
let times = [100, 1000, 10000, 20000];
let promises = [];
for (let time of times) {
promises.push(new Promise((resolve, reject) => {
setTimeout(resolve, time, `${time} is done.`);
}));
}
// obviously, you'd want to generate a real uuid here to avoid collisions
let uuid = uuidV1();
console.log(uuid);
Promise.all(promises).then(values => { JOBS[uuid] = values; });
res.redirect(`progress/${uuid}`);
});
app.get("/progress/:uuid", (req, res) => {
if (JOBS[req.params.uuid] === undefined) {
res.send("Still processing your request.");
} else {
res.send(`Here's your result: ${JOBS[req.params.uuid]}.`);
// instead of immediately deleting the result of the job (and making it impossible for the user
// to fetch it a second time if they e.g. accidentally cancel the download), it would be better
// to run a periodic cleanup task on `JOBS`
delete JOBS[req.params.uuid];
}
});
app.listen(PORT, () => {
console.log(`Listening on localhost:${PORT}.`);
});
当代码运行时,您将被重定向到/ process / uuid,我将获得该进程的状态。
这需要一些改进,因为我想要像" {process:uuid}"我可以将它存储在我的本地存储上以便在之后使用。
嗯,我希望这对某人有所帮助。