使用 Promises 延迟 forEach 循环中的继续
Using Promises to defer continuation within a forEach loop
我的目标是:
- 捕获分辨率列表
- (按顺序)浏览每一个以找到第一个导致成功流的
为了测试这个,我有 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。我有哪些选择?免责声明 - 我是 promises 的新手,所以上面的代码可能格式不正确。
更新:
测试是按重要性顺序定义的 - 所以我确实需要 resolutionTests[0]
在 resolutionTests[1]
之前解决。
起初,您的 testVideoPresence returns 未定义。它不会那样工作。可以做:
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
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); });
扫描您的代码表明您还有其他与异步相关的问题。
如果试验的顺序不重要,您可以简单地使用 map
结合 Promise.race
来确保解析列表的第一个承诺解析整个列表。您还需要确保您的承诺 return 内的其他承诺 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 并避免进一步测试(因为当找到这个时,链已经已注册)
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
我的目标是:
- 捕获分辨率列表
- (按顺序)浏览每一个以找到第一个导致成功流的
为了测试这个,我有 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。我有哪些选择?免责声明 - 我是 promises 的新手,所以上面的代码可能格式不正确。
更新:
测试是按重要性顺序定义的 - 所以我确实需要 resolutionTests[0]
在 resolutionTests[1]
之前解决。
起初,您的 testVideoPresence returns 未定义。它不会那样工作。可以做:
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
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); });
扫描您的代码表明您还有其他与异步相关的问题。
如果试验的顺序不重要,您可以简单地使用 map
结合 Promise.race
来确保解析列表的第一个承诺解析整个列表。您还需要确保您的承诺 return 内的其他承诺 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 并避免进一步测试(因为当找到这个时,链已经已注册)
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