【问题标题】:await only valid in async function meanwhile i already put "async" in the function [duplicate]等待仅在异步函数中有效,同时我已经在函数中添加了“异步”[重复]
【发布时间】:2021-09-22 19:30:36
【问题描述】:

上面说 await 只对 async 函数有效,但我已经把 async 字放在 (req,res,next) 之前,我是不是编码错了?

const axios = require("axios");
const FormData = require("form-data");
const imageKit = async (req, res, next) => {
if (req.files) {
  try {
    const files = req.files;
    const values = Object.values(files);
    values.map((perArray) => {
      perArray.forEach((item) => {
        if (item.mimetype === "image/jpeg" || item.mimetype === "image/png") {
          const newForm = FormData();
          const encodedFile = item.buffer.toString("base64");
          newForm.append("file", encodedFile);
          newForm.append("fileName", item.originalname);
          const encodedKey = Buffer.from(
            process.env.IMAGE_KIT + ":"
          ).toString("base64");
          const result = await axios({
            method: "POST",
            url: "https://upload.imagekit.io/api/v1/files/upload",
            data: newForm,
            headers: {
              ...newForm.getHeaders(),
              Authorization: `Basic ${encodedKey}`,
            },
          });
        }
      });
    });
  } catch (error) {}
}
};

【问题讨论】:

  • 除非你想改变数组中的值,否则不要使用 map,imo 应该重写,所以你抽象出上传到 imagekit 的代码,即在一个称为上传的方法中,然后使其异步,然后还会删除所有库,如 axios、form-data 等,并保持中间件干净,导入您的帮助脚本,然后使用 bog-standard for 循环遍历要上传的文件

标签: javascript node.js express imagekit


【解决方案1】:

您传递给forEach 的函数不是async,不建议在forEach 中使用async

Using async/await with a forEach loop

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 2022-01-25
    相关资源
    最近更新 更多