【发布时间】:2018-04-10 02:17:27
【问题描述】:
我正在学习使用 Promise 并尝试使用函数式编程来实现代码模块化。我的问题是,当我通过then() 链时,我正在通过中间then() 调用传递参数以供以后使用的函数。
这感觉没有必要,我想我只见树木不见森林。
function getSession(user, pass) {
return new Promise((resolve) => {
// do something with user and pass
resolve(session)
})
}
function getAccount(session) {
return new Promise((resolve) => {
// do something with session - pass through session
resolve([session, account])
})
}
function doThing(session, account) {
return new Promise((resolve) => {
// do something with account - pass through session
resolve([session, thing])
})
}
function doOtherThing(session, thing) {
return new Promise((resolve) => {
// do something with session and thing
resolve(otherThing)
})
}
let example = getSession(user, pass).then(getAccount).then(doThing).then(doOtherThing)
例如,doThing() 被传递给 session 和 account,但只对 account 执行某些操作。但是,由于doOtherThing() 需要session,我通过会话实例,以便该函数可以使用它。
所以为了消除通过这些额外的变量,我想做类似的事情
function getAccount(session) {
return new Promise((resolve) => {
// do something with session
resolve(account)
})
}
function doThing(account) {
return new Promise((resolve) => {
// do something with account
resolve(thing)
})
}
let session = getSession(user, pass)
let thing = getSession(user, pass).then(getAccount).then(doThing)
let example = doOtherThing(session, thing)
如您所见,这些函数中的大多数都返回一个承诺,因此我可以通过在其他地方链接来提高代码模块化。因此,session 和 thing 变量被分配了 Promise。
但是在这种情况下,我只想解决 session 和 thing 中的两个承诺,然后在 doOtherThing(session, thing) 中使用
我尝试了类似的东西
let session = getSession(user, pass).resolve()
let thing = getSession(user, pass).then(getAccount).then(doThing).resolve()
和
let example = doOtherThing(session.resolve(), thing.resolve())
但我收到 resolve is not a function 错误。
我也知道
let session = getSession(user, pass)
let thing = getSession(user, pass).then(getAccount).doThing(account)
let example = doOtherThing(session, thing)
没有意义,因为两个变量中的承诺需要在将它们传递给doOtherThing() 之前解决,但我对如何做到这一点持空白 - 所以这是更多的伪代码,表明我没有想通过会话
我查看了this question,但我不认为我正在尝试做同样的事情。
【问题讨论】:
-
如果您
example是一个接受[user,pass]并返回otherThing的函数,那么您可以对转换[user,pass] => session => thing => [session,thing] => otherThing的函数进行硬编码并使用闭包,但如果函数本身被传递或定义为函数数组?您可以映射它们并使用称为线程的实用程序,可以找到一个示例here
标签: javascript asynchronous promise chaining