无法使用“地图"异步模块中的功能 [英] Cannot use "map" function within async module

查看:62
本文介绍了无法使用“地图"异步模块中的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用node.js异步"模块,需要使用映射"方法.
基本上我有一个包含其他数组的数组.内部数组包含2个元素,一个类型和一个图像文件名.

I am using node.js "async" module and need to use the "map" method.
Basically I have an array that contains other arrays. The inner arrays contains 2 elements, a type and an image filename.

var arr0 = [];
var arr1 = ["type1", "image1.jpg"];
jsonArr.push(obj1);
var arr2 = ["type2", "image2.jpg"];
jsonArr.push(obj2);

对于每个内部数组,我想获取由文件名标识的图像的base64编码,并将此编码字符串添加为数组的第三个元素.

For each inner array, I want to get the base64 encoding of the image identified by the filename and add this encoding string as the third element of the array.

我正在做这样的事情:

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

function getImageEncoding(arr, callback){
    console.log("getEncoding:" + arr + "\n");

    // Get image filename
    image = arr[1];

    // Read file and get base64 encoding
    fs.readFile(image, function(err, original_data){
    var base64Image = original_data.toString('base64');
    console.log("test:" + base64Image + "\n");

        // Modify current arr by appendingthe base64 encoding of the image
        callback(null, arr.push(base64Image));
    });
}

async.map(arr0, getImageEncoding, function(err, results){
console.log("in async.map: " + results + "\n");
});

我知道arr.push(base64Image)东西是不正确的,但是我无法弄清楚如何返回修改后的元素.

I know the arr.push(base64Image) stuff is the thing that is not correct, but I cannot figure out how to return the modified element.

在map(arr,迭代器,回调)文档中,指定为:

In map(arr, iterator, callback) documentation, it is specified:

迭代器被调用,其中包含数组中的一个项目以及完成处理时的回调."

"The iterator is called with an item from the array and a callback for when it has finished processing."

问题是我不知道如何用新数组提供回调.

The thing is I cannot figure out how to feed the callback with the new arrays.

推荐答案

这不起作用,因为getImageEncoding中的callback arr.push 的返回值(即1),而不是arr.push之后的arr,这就是您想要的.

This doesn't work because callback in getImageEncoding is called with the return value of arr.push (which is 1), not arr after arr.push, which is what you want.

function getImageEncoding(arr, callback){
    console.log("getEncoding:" + arr + "\n");

    // Get image filename
    image = arr[1];

    // Read file and get base64 encoding
    fs.readFile(image, function(err, original_data){
    var base64Image = original_data.toString('base64');
    console.log("test:" + base64Image + "\n");

        // Modify current arr by appendingthe base64 encoding of the image
        arr.push(base64Image);
        callback(err, arr);
    });
}

async.map(arr0, getImageEncoding, function(err, results){
console.log("in async.map: " + results + "\n");
});

这篇关于无法使用“地图"异步模块中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆