javascript - Node.js:无法从 array.map() 返回新数组

标签 javascript arrays node.js async-await fs

我正在使用一个名为 Okrabyte 的包从文件夹中的每个图像文件中提取单词。结果应该是一个新数组,其中包含我可以在其他函数中使用的提取文本。

当我运行这个时:

var fs = require("fs");
var okrabyte = require("okrabyte");


fs.readdir("imgs/", function(err, files){
  files.map((file)=>{
    okrabyte.decodeBuffer(fs.readFileSync("imgs/"+ file), (err, data)=>{
      let splitWords = data.split(" ");
      let word = splitWords[0].substr(1);
      console.log(word);
    })
  })
})

控制台记录每个单词。为了返回包含这些单词的数组,我尝试了以下操作:

async function words() {
    await fs.readdir("imgs/", function (err, files) {
        return files.map(async (file) => {
            await okrabyte.decodeBuffer(fs.readFileSync("imgs/" + file), async (err, data) => {
                let splitWords = data.split(" ");
                let word = splitWords[0].substr(1);
                return word
            })
        })
    })
}

var testing = await words();

console.log(testing);

这给出了未定义我尝试过将一切都变成 promise ,我尝试过异步等待,我尝试过将每个单词插入一个新数组并在闭包中返回该数组但没有任何效果 - 我做错了什么?

最佳答案

如果您的映射函数是异步的,那么它会返回一个 promise ,因此您的映射数组实际上是一个 promise 数组。但是您可以使用 Promise.all 来获取该数组的解析值。

此外,您还尝试等待对 fs.readdirokrabyte.decodeBuffer 的调用,它们都接受回调并且返回 promise 。因此,如果您想在那里使用 Promise,则必须手动将它们包装在 Promise 构造函数中。

我会这样做:

async function words() {
    // Wrap `fs` call into a promise, so we can await it:
    const files = await new Promise((resolve, reject) => {
        fs.readdir("imgs/", (err, files) => { err ? reject(err) : resolve(files); });
    });

    // Since map function returns a promise, we wrap into a Promise.all:
    const mapped = await Promise.all(files.map((file) => {
        // Wrap okrabyte.decodeBuffer into promise, and return it:
        return new Promise((resolve, reject) => {
            okrabyte.decodeBuffer(fs.readFileSync("imgs/" + file), (err, data) => {
                if (err) return reject(err);
                const splitWords = data.split(" ");
                const word = splitWords[0].substr(1);
                resolve(word);
            })
        })
    }))

    // Mapped is now an array containing each "word".
    return mapped;
}

var testing = await words();

// Should now log your array of words correctly.
console.log(testing);

关于javascript - Node.js:无法从 array.map() 返回新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48174229/

相关文章:

javascript - 为什么在将 `maxlength` 属性设置为 `input` 时不能使用点表示法?

javascript - 滚动到时自动播放youtube视频(使用youtube api)

javascript - 是否可以在Android中编写一个生成两个数组的函数

node.js - 使用 Mongoose 将嵌入文档保存为对象?

node.js - 异步 Mocha 测试(使用 Chai 断言库)应该失败,但被标记为通过

node.js - 在本地运行现有的 Angular 项目

javascript - 极简原型(prototype)(js框架)

javascript - 确保 AMD 模块在内容脚本之前加载

python - 将方阵缩放/调整为更大的尺寸,同时保留网格结构/图案 (Python)

PHP 数组 : indexed vs keyed