[英]Java Script Promises - If Statement Return Best Practices
我正在編寫一個node.js
函數,該函數根據條件cod返回不同的promise:
if(condition){
return promise.then(() => {
return Promise.resolve(value)
})
}else{
return anotherPromise
}
現在的問題是,如果條件為真,則在實現諾言之后我需要執行一些操作,但在另一種情況下,我只是返回諾言,所以eslint
告訴我嵌套諾言是一種不好的做法。 所以這段代碼對我不起作用:
(() => {
if(condition){
return promise
}
}else{
return anotherPromise
}
}).then(() => {
return Promise.resolve(value)
})
因為使用此代碼,所以在兩種情況下都將執行then
回調。
處理這種情況的最佳做法是什么?
如果您使用經典(ES6 / ES2015 +)Promise語法,則必須鏈接promise(這沒什么不好的!)。
但是,您也可以選擇將代碼拆分為多個函數,以提高可讀性並避免嵌套問題 :
const firstCase = () => ... // returning a promise
const secondCase = () => ... // returning a promise
if (condition) {
return firstCase()
} else {
return secondCase()
}
但是使用ES7 / ES2016 +,您可以使用async / await語法:
// in a "async" function
async function main() {
if (condition) {
await promise // if you need the promise result, you can assign it
return value // the result of an async function is always a Promise.
} else {
return anotherPromise
}
}
或混合兩種解決方案。
一個簡單的建議,(這應該起作用)在resolve的參數中傳遞條件, 然后在then塊中對其進行檢查。 下面的偽代碼將更好地闡明它:
(() => {
if(condition){
return new Promise((resolve,reject)=>{
//Some tasks
resolve(condition)
//Some reject condition
reject()
})
}
else {
return new Promise((resolve,reject)=>{
//Some tasks
resolve(condition)
//Some reject condition
reject()
})
}
}).then((condition) => {
if(condition) {
//Do something
}
else {
//Do Nothing
}
})
eslint告訴我,嵌套諾言是一種不好的做法。
disable the linter on this statement. 只要告訴它可以在此語句禁用lint。 承諾具有精確嵌套的能力,因此您可以在需要時嵌套它們,這就是其中一種情況。 您的代碼很好。
似乎您已經使它復雜化了。 then方法已經返回了一個Promise,因此您無需在其中放入Promise.resolve。
您可以為簡單起見
return condition
? promise.then(() => value)
: anotherPromise
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.