vendredi 5 août 2016

javascript load image return without callback [duplicate]

This question already has an answer here:

The issue:
I am trying to test bandwidth speeds. The code below works, and returns a boolean in the form of a callback. However, my question is how do I get this to return a boolean without the need for callbacks?
I've tried promises, and they seem to only allow the return of console.log() or callback()

function initiateSpeedTestForFeature(feature, callback) {
    download = new Image();
    var startTime, endTime;
    var imageAddr, downloadSize;
    var speedMbps, minSpeed;

    if (feature == "feature") {
        imageAddr = linkArray[0]; 
        downloadSize = 153253; //bytes of actual file.
        minSpeed = 0.69;
    }else if (feature == null) {
        return "Please input a feature: cobrowse, voice, video, all or check."
    };

    // Conduct the test.
    startTime = (new Date()).getTime();
    //The cache-buster doesn’t stop a browser from caching the file, it just prevents it from reusing it. 
    download.src = imageAddr + "?v=" + startTime;

    download.onload = function () {
        endTime = (new Date()).getTime();
        var duration = (endTime - startTime) / 1000;
        var bitsLoaded = downloadSize * 8;
        var speedBps = (bitsLoaded / duration).toFixed(2);
        var speedKbps = (speedBps / 1024).toFixed(2);
        speedMbps = (speedKbps / 1024).toFixed(2);
        console.log(speedMbps);
        if (speedMbps < minSpeed) {
            callback(false);
        }else{
            callback(true);
        };
    };
    download.onerror = function (err, msg) {
        console.log("Invalid image, or error downloading");
    };
};

This is what I want:

function initiateSpeedTestForFeature(feature) {
    ...
    download.onload = function () {
         return true; //or false;
    };
    ...
};

So that:

initiateSpeedTestForFeature(feature) = true // or false; 

instead of (or similar),

initiateSpeedTestForFeature(feature, function(data){ result = data;});

Aucun commentaire:

Enregistrer un commentaire