替代异步/等待 [英] Substitute for async/await

查看:40
本文介绍了替代异步/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我具有最新分数的列表,在某些时候我必须更新这些分数.我有这两个功能可以做到这一点.

In my app I have the list of latest scores which at some point I have to update. I have these 2 functions that does that.

function handleLastestScoresChange() {
            $scope.newLatestScores = [{}];
            getNewLatestScores().then(function () {
                for (var i = 0; i < 10; i++) {
                    firebase.database().ref('Latest/' + i.toString()).set({
                        user: $scope.newLatestScores[i].username,
                        text: $scope.newLatestScores[i].text,
                        speed: $scope.newLatestScores[i].result,
                        Index: i + 1
                    })
                }
            })
        };



async function getNewLatestScores() {
        for (var i = 9; i >= 0; i--) {
            if (i == 0 && firebase.auth().currentUser.isAnonymous === false) {
                $scope.newLatestScores[i] = ({
                    'username': firebase.auth().currentUser.email,
                    'text': document.getElementById('Title').textContent,
                    'result': $scope.wordsperminute
                })
            }
            else if (i == 0 && firebase.auth().currentUser.isAnonymous === true) {
                $scope.newLatestScores[i] = ({
                    'username': "Anonymous",
                    'text': document.getElementById('Title').textContent,
                    'result': $scope.wordsperminute
                })
            }
            else {
                await firebase.database().ref('Latest/' + (i - 1).toString()).once('value').then(function (snapshot) {
                    $scope.newLatestScores[snapshot.val().Index] = ({
                        'username': snapshot.val().user,
                        'text': snapshot.val().text,
                        'result': snapshot.val().speed
                    })
                })
            }

        }
    }

在Firebase中,引用数据库返回Promise,因此在getNewLatestScores函数中,我必须使用async/await来确保所有分数均已读取并且在将它们写入数据库之前已在$ scope.newLatestScores对象中.但是由于不支持异步/等待,现在我的应用无法在Firefox或MS Edge中运行.我想知道是否可以在不使用async/await的情况下达到相同的效果.

In Firebase referring to database returns a Promise so in getNewLatestScores function I had to use async/await to be sure that all the scores have been read and are in my $scope.newLatestScores Object before I write them to database. But now my app won't work for example in Firefox or MS Edge due to no support for async/await. I was wondering if I can have the same effect but without using async/await.

推荐答案

async / await 是诺言使用的语法糖.要将其从您的代码中删除,只需让 getNewLatestScores 返回承诺即可.

async/await are syntactic sugar for promise use. To remove them from your code, just have getNewLatestScores return a promise.

一个精确的副本将使该函数循环中的每个promise都等待上一个:

An exact replica would make each promise in that function's loop wait on the previous one:

function getNewLatestScores() {
   var promise = Promise.resolve();
   for (var i = 9; i >= 0; i--) {
       if (i == 0 && firebase.auth().currentUser.isAnonymous === false) {
           $scope.newLatestScores[i] = ({
               'username': firebase.auth().currentUser.email,
               'text': document.getElementById('Title').textContent,
               'result': $scope.wordsperminute
           });
       }
       else if (i == 0 && firebase.auth().currentUser.isAnonymous === true) {
           $scope.newLatestScores[i] = ({
               'username': "Anonymous",
               'text': document.getElementById('Title').textContent,
               'result': $scope.wordsperminute
           });
       }
       else {
           promise = promise.then(function() {
               return firebase.database().ref('Latest/' + (i - 1).toString()).once('value').then(function (snapshot) {
                   $scope.newLatestScores[snapshot.val().Index] = ({
                       'username': snapshot.val().user,
                       'text': snapshot.val().text,
                       'result': snapshot.val().speed
                   })
               });
           );
       }
    }
    return promise;
}

... 但是,因为回调似乎并不需要串行完成,因此可以将它们并行化,而应尽快将它们全部关闭,然后等待最后以 Promise.all :

...but since the callback doesn't seem to require that these be done in series, you could make them parallel instead by starting them all off as soon as possible, and then just waiting at the end with Promise.all:

function getNewLatestScores() {
   var promises = [];
   for (var i = 9; i >= 0; i--) {
       if (i == 0 && firebase.auth().currentUser.isAnonymous === false) {
           $scope.newLatestScores[i] = ({
               'username': firebase.auth().currentUser.email,
               'text': document.getElementById('Title').textContent,
               'result': $scope.wordsperminute
           });
       }
       else if (i == 0 && firebase.auth().currentUser.isAnonymous === true) {
           $scope.newLatestScores[i] = ({
               'username': "Anonymous",
               'text': document.getElementById('Title').textContent,
               'result': $scope.wordsperminute
           });
       }
       else {
           promises.push(firebase.database().ref('Latest/' + (i - 1).toString()).once('value').then(function (snapshot) {
               $scope.newLatestScores[snapshot.val().Index] = ({
                   'username': snapshot.val().user,
                   'text': snapshot.val().text,
                   'result': snapshot.val().speed
               })
           }));
       }
    }
    return Promise.all(promises);
}

这篇关于替代异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆