尝试以不涉及嵌套 promise 的方式编写以下代码时遇到问题。
function trickyFunction(queryOptions, data) {
return new Promise((resolve, reject) => {
if (data) {
resolve(data);
} else {
// ... a bunch of conditions to check and/or modify queryOptions. These checks and mods
// are vital but only required if data is not passed in. ...
if (anErrorHappensHere) {
reject('Oh no, an error happened');
}
somePromise(queryOptions).then((result) => {
resolve(result);
});
}
}).then((result) => {
criticalOperation1(result);
// the code here is long and shouldn't be duplicated
});
}
我真的不喜欢 somePromise
之后的 .then() 链,因为它在 new Promise
中,但我真的没有找到绕过它的方法。如果我从 promise 中取出条件,那么我将不得不复制 criticalOperation1 代码,这不是这里的一个选项。 else
block 中的条件检查只有在未传入 data
时才会发生。在我的情况下不允许使用其他功能,也不允许使用 async/await就我而言。
有人有什么想法吗?我已经使用 Promises 一段时间了,但是这个让我很困惑。
最佳答案
在这种情况下,我会避免使用 new Promise
语法,而是尽早启动 promise 链
function trickyFunction(queryOptions, data) {
return Promise.resolve()
.then( () => {
if (data) {
return Promise.resolve(data);
} else {
// ... a bunch of conditions to check and/or modify queryOptions. These checks and mods
// are vital but only required if data is not passed in. ...
if (anErrorHappensHere) {
// Could also just throw here
return Promise.reject('Oh no, an error happened');
}
return somePromise(queryOptions);
}
})
.then((result) => {
criticalOperation1(result);
// the code here is long and shouldn't be duplicated
});
}
关于javascript - 有条件地调用一个 promise (或不调用),但将任一结果返回给另一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54527749/