所以我对在 NodeJS 中使用 Promises 还很陌生。我正在尝试根据字符串中的字符通过一些操作动态创建一个 promise 。
//let actions = [];
getPromise = get(srcBucket, srcKey); // Get the image
//Apply transformations to image.
while (transformations.length > 0) {
let op = transformations.charAt(0);
if (op == 'B') {
getPromise.then(image => blur(image));
} else if (op == 'R') {
getPromise.then(image => resize(image));
} else if (op == 'O') {
getPromise.then(image => rotate(image));
} else if (op == 'S') {
getPromise.then(image => sepia(image));
} else if (op == 'C') {
getPromise.then(image => compress(image));
}
transformations = transformations.substring(1);
}
getPromise.then(modified => put(destBucket, destKey, modified))
.then(() => putSAAFOutput(inspector))
.then(() => {
console.log('Success');
return resolve('Success');
})
.catch(error => {
console.error(error);
return reject(error);
});
第一行中的 get 方法从 Amazon S3 获取图像。然后我想根据“transformations”字符串中的字符对该图像进行多次转换。每个转换函数(模糊、调整大小、棕褐色等)都返回自己的 promise 。
当我运行此函数时,没有任何转换应用于图像!任何帮助将不胜感激。
最佳答案
听起来您已经看到修复方法是 getPromise = getPromise.then(...)
。我想我只是补充一点,如果你用一个查找表而不是一个大的 if/else
来干燥它,并迭代累积 promise 链的字符列表,那么这种类型的代码看起来会更干净一些听起来像是 .reduce()
的工作。
let getPromise = get(srcBucket, srcKey); // Get the image
const transformMap = {
B: blur,
R: resize,
O: rotate,
S: sepia,
C: compress
};
//Apply transformations to image.
getPromise = transformations.split("").reduce((p, op) => {
let fn = transformMap[op];
if (fn) {
return p.then(image => fn(image));
} else {
return p;
}
}, getPromise);
return getPromise.then(modified => put(destBucket, destKey, modified))
.then(() => putSAAFOutput(inspector))
.then(() => {
console.log('Success');
return 'Success';
})
.catch(error => {
console.error(error);
throw error;
});
此外,您在 promise 链末尾使用 somePromise.then(resolve).catch(reject)
的事实显然意味着您已将所有这些包装在您自己的内部新的 Promise()
。这样做是一种 promise 反模式,并且没有必要。相反,你可以只返回你已有的 promise 。您可以直接return 'Success'
,而不是resolve('Success');
。而且,您可以直接执行抛出错误
,而不是reject(error);
。
关于javascript - NodeJS,在 While 循环中向 Promise 添加操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915145/