在JS中正确使用async和await?

时间:2019-02-04 17:42:53

标签: javascript async-await

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对象的数组。

1 个答案:

答案 0 :(得分: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