使用Promise推迟forEach循环中的延续

时间:2017-05-19 16:29:14

标签: javascript promise bluebird

我的目标是:

  • 捕获决议列表
  • 扫描每一个(按顺序)以找到导致成功流的第一个

为了测试这一点,我有testVideoPresence

var testCounter = 0;
function testVideoPresence(videoElement) {
    testCounter++;
    if (testCounter >= 5) {
        testCounter = 0;
        return false;
    }
    if (!videoElement.videoWidth || videoElement.videoWidth < 10) { // check to prevent 2x2 issue
        setTimeout(function() {
            testVideoPresence(videoElement); // try again
        }, 500);
    } else if (video.videoWidth * video.videoHeight > 0) {
        return true;
    }
}

如您所见,我使用setTimeout最多递归5次。事情变得棘手:

 resolutionTestBuilder.buildTests().then(function (resolutionTests) {
        // at this point, I have a set of resolutions that I want to try
        resolutionTests.forEach(function (resolutionTest) {
            // then I want to iterate over all of them until I find one that works
            performTest(resolutionTest).then(function (result) {
                video.srcObject = result.mediaStream; // start streaming to dom
                if (testVideoPresence(video)) { // here is the pain point - how do I await the result of this within the forEach?
                    // return the dimensions
                } else {
                    // continue scanning
                }
            }).catch(function (error) {
                logger.internalLog(error);
            });

            // wait to continue until we have our result

        });
    }).catch(function (error) {
        logger.internalLog(error);
    });

function performTest(currentTest) {
        return streamHelper.openStream(currentTest.device, currentTest.resolution).then(function(streamData) {
            return streamData;
        }).catch(function (error) {
            logger.internalLog(error);
        });;
    };

streamHelper.openStream = function (device, resolution) {
    var constraints = createVideoConstraints(device, resolution);
    logger.internalLog("openStream:" + resolution.label + ": " + resolution.width + "x" + resolution.height);
    return navigator.mediaDevices.getUserMedia(constraints)
        .then(function (mediaStream) {
            streamHelper.activeStream = mediaStream;
            return { stream: mediaStream, resolution: resolution, constraints: constraints };
            // video.srcObject = mediaStream; // push mediaStream into target element.  This triggers doScan.
        })
        .catch(function (error) {
            if (error.name == "NotAllowedError") {
                return error.name;
            } else {
                return error;
            }
        });
 };

我试图在继续通过一系列决议之前等待forEach内的结果。我知道我可以使用一些像async / await这样的高级技术,如果我想要转换 - 但我现在仍然坚持使用vanilla JS和promises / bluebird.js。我有什么选择?免责声明 - 我是承诺的新手,因此上述代码可能非常不正确。

更新:

测试按重要性顺序定义 - 因此我需要在resolutionTests[0]之前解析resolutionTests[1]

3 个答案:

答案 0 :(得分:1)

首先,您的testVideoPresence返回undefined。它不会那样工作。可以这样做:

function testVideoPresence(videoElement,callback,counter=0) {
 if(counter>10) callback(false);
    if (!videoElement.videoWidth || videoElement.videoWidth < 10) {
        setTimeout(testVideoPresence, 500,videoElement,callback,counter+1);
    } else if (video.videoWidth * video.videoHeight > 0) {
         callback(true);
    }
}

所以你可以这样做:

testVideoPresence(el, console.log);

现在到了forEach。你不能以任何方式产生forEach。但是你可以编写自己的递归forEach:

(function forEach(el,index) {
  if(index>=el.length) return false;

  performTest(el[index]).then(function (result) {
       video.srcObject = result.mediaStream; // start streaming to dom

       testVideoPresence(video,function(success){
           if(!success) return alert("NOO!");
           //do sth
           //proceed
          setTimeout(forEach,0,el,index+1);
        });
  }).catch(function (error) {
          logger.internalLog(error);
 });
})(resolutionTests,0);//start with our element at index 0

答案 1 :(得分:1)

如果试用顺序不重要,您只需使用mapPromise.race结合使用即可确保解析列表的第一个承诺可以解析整个列表。您还需要确保您的承诺在then内返回其他承诺。

resolutionTestBuilder.buildTests().then(function (resolutionTests) {
    return Promise.race(resolutionTests.map(function (resolutionTest) {
        return performTest(resolutionTest).then(function (result) {
            video.srcObject = result.mediaStream; // start streaming to dom
            return testVideoPresence(video);
        }).catch(function (error) {
            logger.internalLog(error);
        });
    }));
}).catch(function (error) {
    logger.internalLog(error);
});

这当然假设当尺寸不可用时testVideoPresence无法解决。

如果试用顺序很重要,那么reduce方法可能会有效。

这基本上会导致承诺的顺序应用,并且直到所有承诺都得到解决。

然而,一旦找到解决方案,我们将它附加到reduce的收集器,以便进一步的试验也只是返回,并避免进一步的测试(因为到这时发现链已经注册)

return resolutionTests.reduce(function(result, resolutionTest) {
    var nextPromise = result.intermPromise.then(function() {
        if (result.found) { // result will contain found whenver the first promise that resolves finds this
            return Promise.resolve(result.found);   // this simply makes sure that the promises registered after a result found will return it as well
        } else {
            return performTest(resolutionTest).then(function (result) {
                video.srcObject = result.mediaStream; // start streaming to dom
                return testVideoPresence(video).then(function(something) {
                    result.found = something;
                    return result.found;
                });
            }).catch(function (error) {
                logger.internalLog(error);
            });
        }
    );
    return { intermPromise: nextPromise, found: result.found };
}, { intermPromise: Promise.resolve() }); // start reduce with a result with no 'found' and a unit Promise 

答案 2 :(得分:0)

function raceSequential(fns) {
    if(!fns.length) {
        return Promise.resolve();
    }
    return fns.slice(1)
        .reduce(function(p, c) { 
            return p.catch(c);
        }, fns[0]());
}

// "Resolution tests"
var t1 = function() { return new Promise(function(_, reject) { setTimeout(() => reject('t1'), 1000); })};
var t2 = function() { return new Promise(function(resolve) { setTimeout(() => resolve('t2'), 1000); })};
var t3 = function() { return new Promise(function(resolve) { setTimeout(() => resolve('t3'), 1000); })};

var prom = raceSequential([t1, t2, t3])
    .then(function(result) { console.log('first successful result: ' + result); });

扫描您的代码表明您有其他与异步相关的问题。