javascript - 即使在 array.Array 中推入元素之后,循环外也显示为空
问题描述
我正在尝试在 node.js 应用程序中使用 cloudinary 上传多个图像。将每个图像 URL 存储在一个数组中。但是我的数组在循环外是空的。无法理解为什么。
const postCreate = (req,res,next) => {
req.body.post.images = [];
const file_length = req.files.length;
let arr = [];
//console.log(req.files);
new Promise((resolve, reject) => {
req.files.forEach((file,index) => {
i = index;
cloudinary.v2.uploader.upload(file.path)
.then(image => {
//console.log(image);
req.body.post.images.push({
url: image.secure_url,
public_id: image.public_id
});
console.log("array", req.body.post.images);//there array is containing the element which is pushed.
});
console.log("arr", req.body.post.images);//but there it is showing empty array .Can't understand why array is empty.
});
resolve();
}).then(() => {
Post.create(req.body.post)
.then(post => {
//console.log(req.body.post.images);
res.redirect(`/posts/${post.id}`);
}).catch(err => {
console.log('Error will saving posts from db ', err);
return next(err);
});
});
解决方案
第二条日志消息实际上在数组为空时首先被调用,因为 then 块中的代码正在等待异步完成。
推荐阅读
- c# - 在内存中使用 SQLite 运行 EF Core - 未配置数据库提供程序
- php - 大量的 CURL [PHP/Python]
- azure-devops - TFS 扩展 - TF400813: 用户 ... 无权访问此资源
- xpath - XPath concat 函数不起作用
- python - 将非数值数据应用于神经网络
- android - Android:JSONObject 无效值和 Wordpress 的 API
- c# - 从 ObservableCollection 中删除多个项目
- python - 使用python子进程执行命令并隐藏控制台窗口
- swift - 我的水平滚动视图不起作用
- hyperledger-composer - 尝试启动业务网络时出错。最后一个错误是 Error: Error: 14 UNAVAILABLE: Trying to connect an http1.x server