Search code examples
javascriptpromisebluebirdes6-promise

Using Promises - result not returning


I have the following:

    resolutionTestBuilder.buildTests().then(function(tests) {
        var s = tests; // checking result
    });

buildTests looks like this:

resolutionTestBuilder.buildTests = function () {
    Promise.all([createAllResolutions(), deviceScanner.scanDevices()])
        .spread(function (resolutions, videoDevices) {
            var tests = [];
            resolutions.forEach(function (targetResolution) {
                videoDevices.forEach(function (videoDevice) {
                    tests.push({ device: videoDevice, resolution: targetResolution });
                });
            });
            return tests;
        });
}

createAllResolutions looks like this:

 var createAllResolutions = function () {
    for (let y = maxHeight; y >= minHeight; y--) {
       resolutions.push(
          {x:x,y:y}
       );
    }
    return resolutions;
}

And finally, scanDevices looks like this:

deviceScanner.scanDevices = function() {
    navigator.mediaDevices.enumerateDevices().then(function(availableDevices) {
        var videoDevices = [];
        for (var i = 0; i < availableDevices.length; ++i) {
            if (availableDevices[i].kind === 'videoinput') {
                videoDevices.push({ label: availableDevices[i].label || 'camera ' + (videoDevices.length + 1), id: availableDevices[i].deviceId });
            }
        }
        return videoDevices;
    });
}

The behavior that I'm seeing is that the .spread parameters are partially complete - I get resolutions but not videoDevices. This is my first attempt at promises (and bluebird) so I'm probably missing something very fundamental here - what am I doing wrong?


Solution

  • returning from the then callbacks is not enough, you need to return the promise that the then() call creates from the function!

    resolutionTestBuilder.buildTests = function () {
        return Promise.all([createAllResolutions(), deviceScanner.scanDevices()])
    //  ^^^^^^
            .spread(function (resolutions, videoDevices) {
                …
            });
    };
    deviceScanner.scanDevices = function() {
        return navigator.mediaDevices.enumerateDevices().then(function(availableDevices) {
    //  ^^^^^^
            …
        });
    };