最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Substitute for asyncawait - Stack Overflow

programmeradmin3浏览0评论

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
                    })
                })
            }

        }
    }

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.

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
                    })
                })
            }

        }
    }

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.

Share Improve this question asked Mar 11, 2017 at 15:20 Bartosz OciepkaBartosz Ociepka 571 gold badge2 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

async/await are syntactic sugar for promise use. To remove them from your code, just have getNewLatestScores return a 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;
}

...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);
}
发布评论

评论列表(0)

  1. 暂无评论