【发布时间】:2018-02-27 08:03:32
【问题描述】:
Promise 的新手,所以请随意冗长。
我正在编写一个函数“extra_promises_at_start_and_end”,它返回一个承诺做某事。
这个函数可能会立即知道它将失败(即:返回一个被拒绝的承诺)。问题 1:是否有类似 Promise.give_me_a_rejected_promise(..) 的东西,还是我必须像我的代码一样创建一个承诺并拒绝它?
同样,我的函数“extra_promises_at_start_and_end”调用其他返回承诺的函数。在此异步工作链结束时,我需要进行一些最终处理。问题 2a/2b:由于我的函数返回一个 Promise,我需要创建一个 Promise 来完成这最后一点工作。我需要创建一个承诺并立即接受或拒绝它是否正确?有没有 Promise.give_me_a_rejected_promise(..).
我的代码按预期工作,只是感觉我遗漏了一些东西,因此生成了冗余代码。
有问题的代码:
// this is the function that may have redundant code
// see question 1 and 2
function extra_promises_at_start_and_end() {
// fake out some module scope variable that indicates if this call is allowed to proceed or not
let ok_to_proceed = Math.random() > 0.5
// this function "extra_promises_at_start_and_end returns" a promise,
// Question 1: I need to create a Promise just to reject it immediatly?
if (!ok_to_proceed) {
return new Promise((resolve, reject) => { reject("failed before starting anything") }) // feels wrong
}
// do 5 things in sequence
return another_module_promise_to_do_something(1).then(() => {
return another_module_promise_to_do_something(2)
}).then(() => {
return another_module_promise_to_do_something(3)
}).then(() => {
return another_module_promise_to_do_something(4)
}).then(() => {
return another_module_promise_to_do_something(5)
}).then(() => {
// need to do something after the above 5 tasks are done,
console.log("doing something after all 5 things are done")
// this function "extra_promises_at_start_and_end" returns a promise,
// Question 2a: I need to create a promise just to resolve it immediatly?
return new Promise((resolve, reject) => { resolve(); }) // feels wrong
}).catch((id) => {
// this function extra_promises_at_start_and_end returns a promise,
// Question 2b: I need to create one just to reject it immediatly?
return new Promise((resolve, reject) => { reject(id); }) // feels wrong
})
}
这段代码的调用者期待一个承诺。
// run the test
console.log("calling something that will return a promise to let me know when it's done");
extra_promises_at_start_and_end()
.then(() => {
console.log("done :)")
}).catch((id) => { console.log("failed id = " + id) })
最后,一个用于测试我的函数的存根
// pretend this is a complex task (ie: not suitable for inlining)
// done by some other module
// it returns a promise
function another_module_promise_to_do_something(id) {
console.log("starting " + id)
let P = new Promise((resolve, reject) => {
console.log(" inside promise " + id)
setTimeout(() => {
if (Math.random() > 0.1) {
console.log(" finished " + id);
resolve();
} else {
console.log(" failed " + id)
reject(id);
}
}, Math.random() * 1000)
})
return P;
}
如果这是应该的方式,那么请告诉我,我将停止寻找使用 Promise 的正确方式。
【问题讨论】:
-
这可能是您正在寻找的问题 1:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript node.js promise