【问题标题】:Promise returns an object instead of the actual string value [Javascript w/ Firebase]Promise 返回一个对象而不是实际的字符串值 [Javascript w/ Firebase]
【发布时间】:2018-01-19 12:30:25
【问题描述】:

所以我研究了 Promises 并得出结论,通过使用.then,它将“实际执行”其中的异步函数。然后,我继续更新我的代码:

function getCurrentKey(){
		return tailorRef.once('value').then(function(data){
			data.forEach(function(childData){
				if ( (loggedUname == childData.val().tUsername) && (loggedPword == childData.val().tPassword) ){
					Ukey = childData.key;
				}
			});
        return Ukey;
		});
	}
	
	currentKey = getCurrentKey();
	
	console.log("key = " + currentKey);

注意:var currentKey 是全局的

控制台中的预期输出将是key = "some unique key",但它显示key = [object Promise]。我试图将.val() 放在childData.key 之后以实际获取值而不是对象,但它不起作用。

我的 Promise 实现或其结构有问题吗?还是我的结论错了?

【问题讨论】:

  • getCurrentKey 中有两个 return 语句 - 第二个被忽略 - 因此,该函数返回的是由 return tailorRef.once('value').then(function(data){ 返回的 Promise
  • @guest271314 - 不是真的。向不懂异步代码的人解释异步代码是相当困难的
  • @JaromandaX 啊,我的错。对不起,我没有早点意识到。
  • 还有更多问题,因为你需要知道如何使用 Promises

标签: javascript firebase firebase-realtime-database promise


【解决方案1】:

因为第一次返回发生在 resolve 部分执行之前。

如果您真的想打印您的 currentKey,请执行以下操作。

function getCurrentKey(){
 tailorRef.once('value').then(function(data){
        data.forEach(function(childData){
            if ( (loggedUname == childData.val().tUsername) && (loggedPword == childData.val().tPassword) ){
                currentKey = childData.key;
                printCurrentKey(currentKey);
            }
        });
    }); 
}


printCurrentKey(key){
  console.log(key)
}

注意:调用printCurrentKey 时请注意范围。

【讨论】:

  • 我的主要目标不是真正打印它,而是将它存储到全局变量currentKey,以便我可以在其他功能中使用登录用户的密钥。我只是打印它来测试我得到了正确的值。
  • 所以我真正想做的是让函数getCurrentKey()返回与登录框中给定的用户名和密码匹配的相应唯一键。我设想currentKey = getCurrentKey() 会将处理后的唯一键存储到所述变量中
  • 这行不通。您只能将密钥返回给设置全局变量的函数。您的分配currentKey = getCurrentKey() 意味着在 api 调用完成之前发生。程序不会在那里等待,它会继续前进。因此,当 api 调用实际完成时,它会调用注册的回调函数(指向函数的指针)。因此,在您的情况下,您想对 currentkey 执行的任何操作都可以在上面示例中的 printCurrentKey 中完成。
  • 有办法解决吗?还是您告诉我将密钥存储到全局变量中是完全不可能的?
猜你喜欢
  • 2021-10-17
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多