Martin Jeremic
Martin Jeremic

Reputation: 659

How to get javascript callback to work

I have started to learn Javascript recently, and since I'm coming from a Windows development world, I'm having a hard time accepting some JS techniques..

I'm trying to load several pictures at the same time in to a page using a FileReader. I know I need to use asynchronous callbacks, but it seems that I can't get it to work.

Here's my code:

function loadFile(file, callback) {
    var reader = new FileReader();
    reader.onload = function(file) {
        var output = document.createElement('input');
        output.type = 'image';
        output.classList.add('image-responsive');
        output.src = reader.result;

        var x = document.getElementById('OrigName');
        x.appendChild(output);
    }
    loadFile(file, callback);

}

for (var i = 0; i < evt.target.files.length; i++) {
    var file = evt.target.files[i];
    loadFile(file);
}

Can someone please help me fix this?

Upvotes: 0

Views: 78

Answers (2)

PeterS
PeterS

Reputation: 2944

As others have commented, the code isn't correct, for a start you are calling your load function:

loadFile(file);

In the for loop and not specifying a call back. Therefore it's going to be undefined when you want to use it. I'm assuming another function should be made to sendFile and that may be the call back. Overall the code needs some work. Think about the problem again and refactor the code, perhaps using Jasmine to write some unit tests to build the code up step by step.

Upvotes: 0

Clarkie
Clarkie

Reputation: 7550

I think you have misunderstood how callbacks work. You probably want something more like this:

function loadFile(file, callback) {
    var reader = new FileReader();
    reader.onload = function(file) {
        var output = document.createElement('input');
        output.type = 'image';
        output.classList.add('image-responsive');
        output.src = reader.result;

        var x = document.getElementById('OrigName');
        x.appendChild(output);
        return callback(output);
    }

}

evt.target.files.forEach(function (file) {
    loadFile(file, function (output) {
        console.log(output);
    }); 
})

This will console.log the output once each file is loaded. You should note though that the files may be loaded in a different order to the order in the array.

Upvotes: 1

Related Questions