javascript - Promises: return then() when action inside it is finished
问题描述
I am using React-Redux-Express, and I'm trying to upload an image with express-fileupload
. Here is my logic for uploading images in my Express server:
In my Express route I do this with Sequelize
router.put('/:id', function(req, res, next) {
models.Projects.update(
{
title: req.body.title,
img: req.body.img,
description: req.body.description,
},
{
returning: true,
plain: true,
where: {
id: req.params.id,
},
}
)
.then(() => {
if (req.files) {
req.files.imgFile.mv(toRelative(req.body.img), function(err) {
if (err) {
throw new Error('Image saving failed');
}
});
}
})
.then(() => {
models.Projects.findById(req.params.id).then((result) => {
return res.send({
Project: result,
});
});
})
.catch((error) => {
return res.send(String(error));
});
});
The problem is that the last then
is triggered before req.files.imgFile.mv
method is finished moving the image, so the React input component can't find it in the frontend.
Does anyone know how can I create a promise inside the first then
, so only when req.files.imgFile.mv
is finished moving the image the second is triggered?
Thanks!
解决方案
当你有一些基于回调而不是基于 Promise 的东西时,一般的想法是显式地构造一个 Promise 以便它可以在更大的 Promise 链中使用:
.then(() => {
if (!req.files) return; // resolve immediately if there are no files
return new Promise((resolve, reject) => {
req.files.imgFile.mv(toRelative(req.body.img), function(err) {
if (err) return reject('Image saving failed');
resolve();
});
});
})
但是,在这种情况下,省略回调函数来强制req.files.imgFile.mv(
返回 aPromise
本身会更容易:
.then(() => {
// if there are files, then the outer Promise chain will wait
// for the returned Promise to resolve before continuing with the next .then:
if (req.files) return req.files.imgFile.mv(toRelative(req.body.img));
})
推荐阅读
- arduino - ASP.NET Core + ESP32 HTTP 请求,GET 返回代码 200,但内容不可读
- jquery - ASP。NET MVC 数据表类型错误:$(...).DataTable 不是函数
- sql-server - 将###-###-####电话号码转换为字符串而不是数学运算
- sql - 有条件地从不同的表中选择
- python - 如何在 X 轴上设置刻度以仅在值更改时显示?
- java - 如何流式传输地图
> 到列表 包含绝对路径作为字符串? - reactjs - 样式化的组件会导致不需要的重新渲染
- symfony - Symfony 4:如何验证用户身份?
- tensorflow - tensorflow v2.0.0-alpha0 在 Windows 10 上构建错误“swif”
- module - 无法在 GNU prolog 中加载 library(readutil) 模块?