Cannot use “map” function within async module

最后都变了- 提交于 2019-12-01 01:48:35
Nicocube

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");
});

The problem is that you execute your callback with the return value of arr.push as your result, where you really want an array as the result. Just use concat instead:

callback(null, arr.concat(base64Image));

You map it properly. You need to use the callback in the iterator, Try the documentation of after

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

function getImageEncoding(tuple, callback){
    fs.readFile(arr[1], function(err, data){
        if (err) return callback(err)
        callback(null, tuple.concat(data.toString('base64'))
    });
}

after.map(arr0, getImageEncoding, function(err, results){
    console.log("in after.map: " + results + "\n");
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!