javascript - 如何使用 Interval-Promise Node.js 模块链接 Promise?

标签 javascript node.js firebase promise google-cloud-functions

我正在使用“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

https://github.com/andyfleming/interval-promise/blob/078528e4096649a56dd2473986d7a1a7eba7909f/src/index.js#L31

if (currentIteration === settings.iterations || stopRequested) {
  rootPromiseResolve()
  return
}

因此可以做几件事:

  1. 将 status 的值保存到外部作用域变量,并在最后一个 then() 回调中使用它
  2. 直接从传递给 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/

相关文章:

javascript - 使用 Javascript 或 CSS 将某些样式应用于特定元素

javascript - 在 HTML/CSS/JS 中创建一个箭头栏

javascript - 按属性选择 d3.js 数据元素

javascript - Node.js Cheerio 模块 ge

javascript - jQuery 简单修改以在单击一次时禁用单击图像

javascript - node.js http服务器如何获取连接数

css - 网站上的动画

firebase - 在 flutter 中从 Cloud Firestore 获取数据到 ListView

swift - 在使用 queryEqualToValue 查询获取用户信息时,我无法获取具有额外子 [Firebase][Swift] 的用户信息

json - 将 Firebase 实时数据库 json 响应从 _InternalLinkedHashMap<Object?, Object?> 转换为 Map<String,dynamic>