承诺良好实践
Promises Good Practice
快速提问。
对于复杂的 Promise 函数,这样组织代码是否更好:
一个独特的功能,每个功能都尽可能小
var a = () => {
return new Promise((resolve, reject) => {
return promise1().then((result1) => {
return promise2(result1)
}).then((result2) => {
return promise3(result2)
}).then((result3) => {
return promise4(result3)
}).then((result4) => {
resolve(result4)
}).catch((error) => {
reject(error)
})
}
或者像这样
将一些复杂性封装到其他函数中以获得更简单的高级函数。
var b = () => {
return new Promise((resolve, reject) => {
return promise12().then((result12) => {
return promise34(result12)
}).then((result4) => {
resolve(result4)
}).catch((error) => {
reject(error)
})
})
}
var promise12 = () => {
return new Promise ((resolve, reject) => {
return promise1().then((result1) => {
return promise2(result1)
}).then((result2) => {
resolve(result2)
}).catch((error) => {
reject(error)
})
})
}
var promise34 = (result2) => {
return new Promise ((resolve, reject) => {
return promise3().then((result3) => {
return promise4(result4)
}).then((result) => {
resolve(result4)
}).catch((error) => {
reject(error)
})
})
}
没有 "best way" 来组织您的代码。您应该考虑将您的功能分成逻辑模块,以便它们的用法是 "intuitive".
此外,您还没有提到 Max Stoiber 的 generators
(functions with *
next to them), which is a new javascript ES6 feature. Very likely that in the future these generator function will be a 'de facto' way to handle asynchronous code, because they are well designed to handle it. They are also easy to read and test. You can watch this (currently) free course 来了解更多关于它们的信息。本课程专门设计用于展示如何使用生成器函数编写异步代码。
快速提问。
对于复杂的 Promise 函数,这样组织代码是否更好:
一个独特的功能,每个功能都尽可能小
var a = () => {
return new Promise((resolve, reject) => {
return promise1().then((result1) => {
return promise2(result1)
}).then((result2) => {
return promise3(result2)
}).then((result3) => {
return promise4(result3)
}).then((result4) => {
resolve(result4)
}).catch((error) => {
reject(error)
})
}
或者像这样
将一些复杂性封装到其他函数中以获得更简单的高级函数。
var b = () => {
return new Promise((resolve, reject) => {
return promise12().then((result12) => {
return promise34(result12)
}).then((result4) => {
resolve(result4)
}).catch((error) => {
reject(error)
})
})
}
var promise12 = () => {
return new Promise ((resolve, reject) => {
return promise1().then((result1) => {
return promise2(result1)
}).then((result2) => {
resolve(result2)
}).catch((error) => {
reject(error)
})
})
}
var promise34 = (result2) => {
return new Promise ((resolve, reject) => {
return promise3().then((result3) => {
return promise4(result4)
}).then((result) => {
resolve(result4)
}).catch((error) => {
reject(error)
})
})
}
没有 "best way" 来组织您的代码。您应该考虑将您的功能分成逻辑模块,以便它们的用法是 "intuitive".
此外,您还没有提到 Max Stoiber 的 generators
(functions with *
next to them), which is a new javascript ES6 feature. Very likely that in the future these generator function will be a 'de facto' way to handle asynchronous code, because they are well designed to handle it. They are also easy to read and test. You can watch this (currently) free course 来了解更多关于它们的信息。本课程专门设计用于展示如何使用生成器函数编写异步代码。