javascript - 数组填充了 4 个项目,但长度为 0
问题描述
我正在使用 javascript,当我推送项目时,数组返回 0 长度并且它记录为空,但是当我展开它时,它会显示它有项目。
编码:
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
asyncForEach(image, imageUpload => {
RNFetchblob.fetch('POST', SERVICE_URL + 'uploadImage.php', {
Authorization : "Bearer access-token",
otherHeader : "foo",
'Content-Type' : 'multipart/form-data',
}, [
{ name : 'image', filename : 'image.png', type:'image/png', data: imageUpload.data},
]).then((resp) => {
const response = Object.values(resp)
response.forEach(img => images.push(img))
}).catch((err) => {
})
})
console.log(images)
解决方案
您创建的函数是异步的,但调用它的主要代码不是。你asyncForEach
返回一个承诺,代码继续运行。
您需要将日志记录命令.then()
附加到其结果中,或者使您的外部功能异步,这几乎是同一件事。
另一个问题是你在循环中等待你的承诺,这意味着在第一个图像完成之前你不会开始加载第二个图像,等等。更好的选择是创建一个承诺数组并将它们传递给Promise.all
:
Promise.all(image.map(imageUpload => RNFetchblob.fetch(...).then(...))
.then(() => console.log(images));
(需要注意的是,如果其中一个上传失败,promise 将立即拒绝并打印到目前为止收集的结果,这可能是空的。请注意,剩余的上传仍将继续运行,因此它只会影响控制台输出。它可以可以通过在 之后添加.catch
子句来避免then
,但请确保以某种方式通知自己错误。)
推荐阅读
- cassandra - 为什么“bash:cqlsh:找不到命令”
- html - reactjs为表格单元格着色
- r - 如何在 ifelse 语句中更新我的 sample()?
- javascript - 如何将工作 HTML、CSS、Javascript 代码从 Codepen 传输到 Visual Studio 代码和浏览器
- mysql - Sql 在简单查询上抛出错误
- c# - 当sql语句包含@时如何将Dapper与mysql一起使用
- html - 没有 javascript 的交互式页面加载
- cakephp - fontawesome-webfont.ttf:1 在 cakephp 2.10.12 中找不到
- excel - 将数字存储为文本时如何使用带有大于或等于运算符的 Excel SUMIFS
- python - 如何在 Flask-SQLAlchemy 中按用户获取不同列条目的数量?