我正在使用“interval-promise”( github repo here ) 模块读取 Firebase 实时数据库 Node 中的值以进行持续登录。
这个想法是从可能尚不存在的实时数据库 Node 读取“状态”键,并重试直到它具有值。
const tryGetAuthStatus = (user) =>
new Promise((resolve, reject) => {
var login_node = user.child(provider);
if (login_node.exists()) {
resolve(login_node.val().status)
}
})
ref.child(uuid).once('value') //Returns a promise
.then((user) =>
intervalPromise(
async (iteration, stop) => await tryGetAuthStatus(user), //Returns a promise
attempts_pause,
{ iterations: attempts_max, stopOnError: true }
)
)
.then((result) => console.log(result)) //undefined
如您所见,我返回了 IntervalPromise Promise 以继续 Promise 链。 当从 firebaseTryGetAuth 返回的 Promise 解析时,它会返回正确的结果(例如“已授权”),但链中的最后一个“then”不会从返回的 IntervalPromise 中获取任何结果。
如何传播结果?
最佳答案
interval()
返回的 Promise 不会解析/传递您自己的异步操作中的 long 值。它只是调用 resolve()
来结束自己的 promise
if (currentIteration === settings.iterations || stopRequested) { rootPromiseResolve() return }
因此可以做几件事:
- 将 status 的值保存到外部作用域变量,并在最后一个
then()
回调中使用它 - 直接从传递给
interval()
的函数检查状态
//only use in then() callback
//outside use may result in use before set
let authStatus = null;
let authCheck = (user)=>{
return async (iteration, stop) => {
let status = await tryGetAuthStatus(user)
//set variable for use in then()
authStatus=status;
//or check status now and do so some action
//instead of in some later then()
if(status == whatyouwant){
someAction()
//call stop() since no reason to continue
//the async loop
stop();
}
};
};
ref.child(uuid).once('value')
.then((user) =>
intervalPromise(
authCheck(user),
attempts_pause,
{ iterations: attempts_max, stopOnError: true }
)
)
//if you want to go the set outer scope variable route
.then(() =>{
if(authStatus == whatever){
doSomeAction();
}
})
关于javascript - 如何使用 Interval-Promise Node.js 模块链接 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58931470/