有条件地承诺(或没有),但在回报导致另一个承诺
遇到问题尝试写下面的代码中不涉及嵌套的承诺的一种方式。
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
后。那么()链,因为它的new Promise
里面,但我实在看不出办法解决它。如果我参加了有条件遵守诺言,那么我不得不重复criticalOperation1代码,这是不是一种选择这里。如果else
未传递的data
块的条件检查应该只发生。制作等功能于我的情况是不允许的,并使用异步/等待也没有我的情况下允许的。
有没有人有什么想法?我已经承诺了一点工作,但这个被绊倒了我。
回答如下:我只想避免使用new 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
});
}
有条件地承诺(或没有),但在回报导致另一个承诺
遇到问题尝试写下面的代码中不涉及嵌套的承诺的一种方式。
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
后。那么()链,因为它的new Promise
里面,但我实在看不出办法解决它。如果我参加了有条件遵守诺言,那么我不得不重复criticalOperation1代码,这是不是一种选择这里。如果else
未传递的data
块的条件检查应该只发生。制作等功能于我的情况是不允许的,并使用异步/等待也没有我的情况下允许的。
有没有人有什么想法?我已经承诺了一点工作,但这个被绊倒了我。
回答如下:我只想避免使用new 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
});
}