Javascript 有条件地调用承诺(或不调用),但将其中一个结果返回给另一个承诺
在尝试以不涉及嵌套承诺的方式编写以下代码时遇到困难Javascript 有条件地调用承诺(或不调用),但将其中一个结果返回给另一个承诺,javascript,node.js,asynchronous,promise,Javascript,Node.js,Asynchronous,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 che
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()链,因为它在新的Promise
中,但我真的看不到解决它的方法。如果我从承诺中去掉条件,那么我必须复制criticalOperation1代码,这在这里不是一个选项。else
块中的条件检查只应在未传入数据的情况下进行。在我的情况下不允许生成其他函数,在我的情况下也不允许使用async/await
有人有什么想法吗?我已经与Promises合作了一段时间,但这一次让我很难堪。在这种情况下,我会避免使用新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
});
}
您应该学习promise async/await的新语法。@AshokPatidar请阅读我的问题,我提到这在我的案例中是不允许的。fyi,没有理由执行返回promise.resolve(数据)代码>在处理程序中。然后()
处理程序。您只需执行返回数据代码>。
function trickyFunction(queryOptions, data) {
return new Promise((resolve, reject) => {
if (anErrorHappensHere) {
reject('Oh no, an error happened');
}
resolve({data, queryOptions});
}).then((obj) => {
if(obj.data){
return Promise.resolve(obj.data);
} else {
return somePromise(obj.queryOptions)
}
}).then((result) => criticalOperation1(result));
.catch((err)=> console.log(err));
}