【问题标题】:Using Promises - result not returning使用 Promises - 结果不返回
【发布时间】:2017-10-19 18:55:09
【问题描述】:

我有以下几点:

    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。这是我第一次尝试承诺(和蓝鸟),所以我可能在这里遗漏了一些非常基本的东西——我做错了什么?

【问题讨论】:

  • resolutionTestBuilder.buildTests 不返回任何内容? deviceScanner.scanDevices 也没有
  • @JaromandaX - 我试图在这里返回tests - 我想我真的把流程搞砸了。我应该回报承诺吗?
  • return Promise.all ....return navigator.mediaDevices.enumerateDevices().then ... 等可能是票...就像任何功能一样,如果您不返回任何内容,则不会返回任何内容(从技术上讲,undefined 会返回)跨度>
  • @JaromandaX 做到了 - 谢谢 :)

标签: javascript promise bluebird es6-promise


【解决方案1】:

来自then 回调的returning 是不够的,您需要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) {
//  ^^^^^^
        …
    });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-30
    • 2018-01-21
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多