如何先从Firebase获取结果,然后重定向到另一个页面

How to get the result from firebase first and then redirect to another page?

本文关键字:重定向 另一个 然后 何先 Firebase 获取 结果      更新时间:2023-09-26

我的应用程序中有一个函数可以从Firebase获取一些数据,在完成Firebase on函数后,我需要将其重定向到另一个页面。但是在我的代码中,当我按下按钮时,它会迅速重定向到另一个 bage,因此不会处理该函数。我该怎么做?

 $('#pg-myb-inde #testBtn').on('click',function(){
         myFirebaseRef.orderByChild('emailid').equalTo('mishan@gmail.com').on('value',function(userSnap){
            var user=userSnap.val();
//            $('#UserPage .person-name').empty();
//            $('#UserPage .person-name').append('' +
//                '<i class="glyphicon glyphicon-th-list"></i> '+user.fname);
            console.log('appended');
            console.log(user.fname);

        });
        location.href = "/another-web-page";
    })

这是你要找的吗?

$('#pg-myb-inde #testBtn').on('click',function(){
    var query = myFirebaseRef.orderByChild('emailid').equalTo('mishan@gmail.com');
    query.on('value',function(userSnap){
        var user=userSnap.val();
        location.href = "/another-web-page";
    });
})

我唯一更改的是将位置的设置移动到回调函数

如果这确实是您要查找的内容,那么将一些日志记录语句放入此代码可能会有所帮助:

$('#pg-myb-inde #testBtn').on('click',function(){
    var query = myFirebaseRef.orderByChild('emailid').equalTo('mishan@gmail.com');
    console.log('Before Firebase query');
    query.on('value',function(userSnap){
        console.log('In Firebase callback');
        var user=userSnap.val();
        location.href = "/another-web-page";
    });
    console.log('After Firebase query');
})

现在,当您运行此代码时,输出很可能不是您期望的:

Before Firebase query
After Firebase query
In Firebase callback

原因是数据是从 Firebase 异步检索的。当您调用on()时,它会启动对服务器的请求。但是,由于可能需要一段时间才能从服务器返回响应,因此您的浏览器不会等待答案,而只是在查询继续使用代码。当数据从服务器返回时,将调用您的回调。