Javascript 处理需要10+;秒
我希望这个问题不要太笼统,但我收到了一个post请求,该请求会上载一个高分辨率图像,然后在服务器端,对该图像执行若干操作以生成缩略图和水印。服务器需要10-20秒的时间才能最终返回响应。我应该返回某种临时响应吗?这里有最佳实践吗 为了便于说明,下面是客户端代码的大致轮廓:Javascript 处理需要10+;秒,javascript,node.js,ajax,axios,Javascript,Node.js,Ajax,Axios,我希望这个问题不要太笼统,但我收到了一个post请求,该请求会上载一个高分辨率图像,然后在服务器端,对该图像执行若干操作以生成缩略图和水印。服务器需要10-20秒的时间才能最终返回响应。我应该返回某种临时响应吗?这里有最佳实践吗 为了便于说明,下面是客户端代码的大致轮廓: axios.post('/upload', hugePhoto, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(res => { /* tak
axios.post('/upload', hugePhoto, { headers: { 'Content-Type': 'multipart/form-data' } })
.then(res => { /* takes 10-20 seconds before I get a response here */ })
.catch(err => { /* handle error */ })
服务器端代码,请注意,我在这里创建了一组不同大小的图像,并将它们上传到S3,这需要很长时间:
router.post('/upload', upload.single('file'), (req, res) => {
sharp(req.file.path).metadata()
.then(m => /* reading metadata */)
.then(() => /* some db operations */)
.then(() => /* uploading original file to S3 */)
.then(() => /* resizing the file with sharp */)
.then(() => /* uploading that to S3 */)
.then(() => /* resizing the file with sharp */)
.then(() => /* uploading that to S3 */)
.then(() => /* resizing the file with sharp */)
.then(() => /* uploading that to S3 */)
.then(() => res.json({ success: true }))
.catch(err => res.status(400).send(err.message))
})
谢谢大家! 这是使用无服务器事件驱动体系结构的完美用例。客户端不需要等到您创建并上传不同分辨率的图像。有多种方法可以减少时间
希望它能给你一些想法。你也能发布你的服务器代码吗?我可以发布一些东西,让你大致了解一下……备用1方案是服务器立即响应端点,客户端可以在响应准备就绪后轮询响应。尽管考虑到目前为止您提供的详细信息,这可能不会给您带来任何好处。@junvar客户端如何知道端点何时准备就绪?我不熟悉poll?对于评论部分来说有点复杂,但是一旦你发出第一个请求,你就会在服务器上启动一个任务来处理图像,然后立即返回“稍后检查”响应。然后你可以设置一个socket或
setInterval
到一个端点,当任务完成时可以更新客户端。我在过去几天里一直在研究这个问题,并认为不需要,构建lambda函数是一件过分的事,但我越深入这个项目,这个选项就越好。非常感谢。
router.post('/upload', upload.single('file'), (req, res) => {
sharp(req.file.path).metadata()
.then(m => /* reading metadata */)
.then(() => /* some db operations */)
.then(() => /* uploading original file to S3 */)
.then(() => Promise.all([funcResolution1(), funcResolution2(), funcResolution3()]))
.then(() => res.json({ success: true }))
.catch(err => res.status(400).send(err.message))