使用Promises - 结果不返回

时间:2017-05-19 15:11:26

标签: javascript promise bluebird es6-promise

我有以下内容:

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

buildTests看起来像这样:

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看起来像这样:

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

最后,scanDevices看起来像这样:

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

我看到的行为是.spread参数部分完成 - 我得到resolutions但不是videoDevices。这是我对承诺(和蓝鸟)的第一次尝试,所以我可能在这里遗漏了一些非常基本的东西 - 我做错了什么?

1 个答案:

答案 0 :(得分:2)

来自return回调的{p> then是不够的,您需要return then()来自该函数的调用的承诺!

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