我有一个函数可以将 Canvas 图像重新采样到第二个 Canvas 。据我所知,通过使用 then
,它使用了 promises 并帮助我获得延迟的 return
,而不是得到一些 undefined if 返回
来得太早了。
function resample_sizeo(canvas, width, height) {
// Initialize
var resizer = sizeo();
var canvasResampled = document.createElement('canvas');
canvasResampled.width = width;
canvasResampled.height = height;
// Function using two canvas' in the form of: resize(from, to)
return resizer.resize(canvas, canvasResampled)
// Function that converts resampled canvas to a data blob
.then(result => resizer.toBlob(result, 'image/jpeg', 95))
// End with a blob to return
.then(blob => blob);
}
我希望将 n 次 resample_sizeo
调用链接在一起并按顺序运行它们。我看到这是一个很受欢迎的请求,而且我还看到它通过 await/async
得到了很好的解决,但我还不能使用它们,原因我不会在这里讨论。
我非常接近于使用一些脚本,例如 Promise-Waterfall但是发现我试图满足它的返回 promise 函数数组的尝试使我的代码加倍,而且 - 也许 - 如果我已经有一个返回 promise 的函数,我会做很长的路要走。也许我把一些简单的事情复杂化了,我已经完成了 90% 的工作。所以我试着回到我的 friend 身边 then
。当然,如果我的函数已经返回一个 promise ,我可以将对函数的一些调用链接在一起吗?
resample_sizeo(sourceCanvas, widthsRequired[0], heightsRequired[0])
.then(function(result) { // (**)
console.log(result);
resampledImageBlobs[0] = result;
resample_sizeo(sourceCanvas, widthsRequired[1], heightsRequired[1])
}).then(function(result) { // (***)
resampledImageBlobs[1] = result;
resample_sizeo(sourceCanvas, widthsRequired[2], heightsRequired[2])
}).then(function(result) {
resampledImageBlobs[2] = result;
resample_sizeo(sourceCanvas, widthsRequired[3], heightsRequired[3])
}).then(function(result) {
resampledImageBlobs[3] = result;
console.log("All done", resampledImageBlobs);
uploadImageBlobSet(resampledImageBlobs, 'replace');
});
这没有用。 resampledImageBlobs
表明它在末尾是 [blob,undefined,undefined,undefined],因此它不会在到达末尾之前等待每个函数完成。我忽略了一些东西。如果我单独检查这些调用中的任何一个的结果,它们都会返回一个 blob。但它们并没有按顺序链接并依次等待。
最佳答案
您需要从 resample_sizeo
返回 promise 。否则,您对 .then(...)
的下一次调用将立即运行,并且 result
参数将是函数的通常返回值,即 undefined
:
resample_sizeo(sourceCanvas, widthsRequired[0], heightsRequired[0])
.then(function(result) { // (**)
console.log(result);
resampledImageBlobs[0] = result;
return resample_sizeo(sourceCanvas, widthsRequired[1], heightsRequired[1])
}).then(function(result) { // (***)
resampledImageBlobs[1] = result;
return resample_sizeo(sourceCanvas, widthsRequired[2], heightsRequired[2])
}).then(function(result) {
resampledImageBlobs[2] = result;
return resample_sizeo(sourceCanvas, widthsRequired[3], heightsRequired[3])
}).then(function(result) {
resampledImageBlobs[3] = result;
console.log("All done", resampledImageBlobs);
uploadImageBlobSet(resampledImageBlobs, 'replace');
});
关于javascript - Promise returns in a chain 的误解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660266/