【问题标题】:TypeError: #<Promise> is not a functionTypeError: #<Promise> 不是函数
【发布时间】:2021-03-16 11:41:41
【问题描述】:

我在 3 天前尝试从后端读取图像,这是我尝试过的最佳解决方案,但出现错误并且不理解错误

请帮忙

  get_image:(req,res)=>{
const directoryPath = __basedir + "/uploads/";
const baseUrl = "http://localhost:8080/test/get_image/";
fs.readdir(directoryPath,  function (err, files) {
  if (err) {
    res.status(500).send({
      message: "Unable to scan files!",
    });
  }
  let fileInfos = [];
  files.forEach(Image.findAll().then(data=>{   <<=== error here 
    fileInfos.push({
      name: data.name,
      url:  baseUrl+data.name,
    });
  }))
})
   }

错误:

 files.forEach(Image.findAll().then(data=>{
        ^
TypeError: #<Promise> is not a function

【问题讨论】:

  • .forEach( foo ) 期望 foo 是一个将为每个元素执行的函数。但是,在您的情况下,foo = Image.findAll().then( /* ... */ ) 这是一个承诺,而不是一个功能。
  • 您已将Promise 传递给files.forEach(...) 而不是回调函数。
  • 同样的问题:files.forEach(foo) =>TypeError: # is not a function
  • 这正是我试图解释的......你不能将承诺传递给forEach。而且我不知道你想做什么,所以我不能告诉你正确的代码是什么。

标签: node.js express promise


【解决方案1】:

试试这个:

  get_image: (req, res) => {
    const directoryPath = __basedir + "/uploads/";
    const baseUrl = "http://localhost:8080/test/get_image/";
    fs.readdir(directoryPath, async function(err, files) {
      if (err) {
        res.status(500).send({
          message: "Unable to scan files!"
        });
      }
      let data = await Image.findAll();
      let fileInfos = files.map(file => ({
        name: data.name,
        url: baseUrl + data.name
      }));
    });
  }

您可以一次获取数据然后映射它,而不是一遍又一遍地迭代

【讨论】:

【解决方案2】:

替换你的代码块

files.forEach(Image.findAll().then(data=>{   <<=== error here 
    fileInfos.push({
      name: data.name,
      url:  baseUrl+data.name,
    });
  }))

const responseList = await Promise.all(
    files.map(() => {
        return Image.findAll().then(data => {
            return fileInfos.push({
                name: data.name,
                url: baseUrl + data.name,
            });
        })
    })
)

然后它将起作用。我已经使用 Promise.all 并行运行所有请求

【讨论】:

  • responseList 将未定义
  • files.forEach(...) 将返回 undefined 到 Promise.all(...),这就是 responseList 的值。你不能从.forEach() 方法返回任何东西。
  • @Ifaruki 谢谢更正。实际上我没有在 IDE 中编写这就是为什么会出错
猜你喜欢
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-18
  • 2019-10-31
  • 2018-07-08
  • 2017-09-24
  • 1970-01-01
相关资源
最近更新 更多