[英]Pass a function into a Promise ES6
I've seen questions similar to this in various forms but I can't seem to crack this particular case...我已经以各种形式看到过与此类似的问题,但我似乎无法破解这个特殊案例......
I want to pass a function inside a Promise, then execute that Promise and do something with the result.我想在 Promise 中传递一个函数,然后执行该 Promise 并对结果做一些事情。 The function to be passed in is the database transaction txn
function below:要传入的函数是下面的数据库事务txn
函数:
db.transaction(txn => {
//lodash reduce function to execute each promise sequentially
_.reduce(promisesToExecute, (pending, next, i) => {
return next
//this bit is wrong but I don't know how else to pass in txn
//how should I pass txn into the promise?
.then(fn => fn(txn))
.then(newIds => {
if (newIds) {
returnContent[i] = newIds
}
return next
})
}, Promise.resolve())
})
And the promise I want to execute is here我要执行的承诺就在这里
(newVals, id, fkId) => {
return new Promise((resolve, reject) => {
return txn => {
//I want txn to be available in here to use
return db.table('Users')
.insert(newVals)
.transacting(txn)
.then(res => {
resolve(res.id)
})
.catch(err => {
reject(err)
})
}
})
Any ideas?有任何想法吗? Do I need to somehow pass the newIds => {}
function in as a callback?我是否需要以某种方式将newIds => {}
函数作为回调传递newIds => {}
?
The problem here is that you're creating promises that will never resolve.这里的问题是您正在创建永远无法解决的承诺。 They have a function inside them that never gets called, and the resolve
and reject
hang off of that function.它们内部有一个永远不会被调用的函数,并且resolve
和reject
挂在该函数上。
So fix your second chunk of code to return functions, not promises:所以修复你的第二段代码以返回函数,而不是承诺:
(newVals, id, fkId) =>
txn =>
db.table('Users')
.insert(newVals)
.transacting(txn)
.then(res => res.id)
Then fix the first chunk of code accordingly:然后相应地修复第一块代码:
db.transaction(txn =>
_.reduce(functions, (pending, next, i) =>
next(txn)
.then(newIds => {
if (newIds) {
returnContent[i] = newIds
}
})
, Promise.resolve())
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.