【问题标题】:proper usage of async and await in JS?在JS中正确使用异步和等待?
【发布时间】:2019-02-05 03:39:52
【问题描述】:
import Firebase from './Firebase'
import videoManager from './videoManage';

   async function getAllDatabaseLocations() {
        await let ref = Firebase.database().ref("locations")
        var user_locations = [];
        ref.on("value", function (snapshot) {
            snapshot.forEach(function (datas) {
                const data = datas.val();

                vid_manage = new videoManager(data.videourl);
                vid_ref = vid_manage.getLocationVideoUrl();
                vid_ref.getDownloadURL().then(function (url) {
                    videourl = url;
                   }).catch(function (error) {
                });
                let lokation = data.lokation;
                let videourl = data.videourl;
                let openinghours = data.openinghours;
                let links = data.links;

                let Lokationer = {
                    lokation: lokation,
                    videoUrl: videourl,
                    openingshours: openinghours,
                    links: links
                };

                console.log("Location objects are: ", Lokationer);
                user_locations.push(Lokationer);
                // location_obj.push(Lokationer);

            });                
        });
        return user_locations;
    }

export default getAllDatabaseLocations;

这个方法总是返回一个空数组,即使循环内的控制台按我预期的那样打印?如何使用 async 和 await 属性来返回一个包含所有 Lokationer 对象的数组。

【问题讨论】:

  • 等待将在异步函数或返回承诺的函数之前进行。我不能说这是否适用于您的 Firebase 呼叫,但如果是,您会将 await 放在分配中 = 的右侧,就在您想要等待结果的呼叫之前。所以let ref = await Firebase.[...]

标签: javascript async-await


【解决方案1】:

由于异步 ref.on("value") 回调,您需要返回一个新的 Promise。

function getAllDatabaseLocations() {
  return new Promise(resolve => {
    ref.on("value", function (snapshot) {
      ...
      // when done filling the array
      resolve(user_locations);
    });
  });
}

const userLocations = await getAllDatabaseLocations(); // user_locations

【讨论】:

  • 谢谢。我让它工作了。但我无法将所有对象推入 user_locations 数组。只有少数对象被推送到 user_locations。
猜你喜欢
  • 2018-05-17
  • 2020-09-10
  • 1970-01-01
  • 2019-03-03
  • 2017-01-24
  • 2020-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多