約束が新しくなるので、冗長でも構いません。開始時の余分な約束と終了時の余分な約束
私は何かをする約束を返す関数 "extra_promises_at_start_and_end"を書いています。
この関数は、失敗する(つまり、拒否された約束を返す)ことをすぐに知っているかもしれません。質問1:Promise.give_me_a_rejected_promise(..)のようなものがありますか、私のコードのように約束をして拒否しなければなりませんか?
同様に、私の関数 "extra_promises_at_start_and_end"は、約束を返す他の関数を呼び出します。この非同期チェーニングの最後に、私はいくつかの最終処理が必要です。質問2a/2b:私の関数は約束を返すので、この最後の仕事をするという約束をする必要があります。これは正しいですか?私は約束を作成し、すぐにそれを受け入れるか拒否する必要がありますか? 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;
}
私の機能をテストするためのスタブ。
これは、あなたが、質問1のために探しているものはおそらくです:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/reject –