首页 > 解决方案 > 数组填充了 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)

标签: javascriptandroidiosarraysreactjs

解决方案


您创建的函数是异步的,但调用它的主要代码不是。你asyncForEach返回一个承诺,代码继续运行。

您需要将日志记录命令.then()附加到其结果中,或者使您的外部功能异步,这几乎是同一件事。

另一个问题是你在循环中等待你的承诺,这意味着在第一个图像完成之前你不会开始加载第二个图像,等等。更好的选择是创建一个承诺数组并将它们传递给Promise.all

Promise.all(image.map(imageUpload => RNFetchblob.fetch(...).then(...))
  .then(() => console.log(images));

(需要注意的是,如果其中一个上传失败,promise 将立即拒绝并打印到目前为止收集的结果,这可能是空的。请注意,剩余的上传仍将继续运行,因此它只会影响控制台输出。它可以可以通过在 之后添加.catch子句来避免then,但请确保以某种方式通知自己错误。)


推荐阅读