Angularjs Error: regeneratorRuntime is not defined

2020-04-26 23:48发布

I am working with angularjs and i want to execute some code related to reading files data and i want execute this function totally then start to execute another block of code.

science i have used "async" keyword in my controller i got this error

regeneratorRuntime is not defined

and this is my async function definition:

 async function fillFilesData() {
            if (uploader.queue.length) {
                uploader.queue.forEach(function (item) {
                    var reader = new FileReader();
                    reader.onloadend = function (e) {
                        console.log("about to encode");
                        var encoded_file = btoa(e.target.result.toString());
                        $scope.newAnnouncement.files.push({ fileName: item.file.name, encodedDatta: encoded_file });
                    };
                    reader.readAsBinaryString(item._file);

                });


            }

}

function calling:

$scope.add = function () {
            fillFilesData().then(function () {
//rest of my code here here
}
)};

1条回答
孤傲高冷的网名
2楼-- · 2020-04-27 00:23

Async and await are being transpiled into generator functions or something that resembles them if the target browser/node version in your babelrc doesn't support them and you don't have the babel-plugin-transform-runtime plugin installed. There's several ways this can be resolved, ie installing preset-env, or babel-plugin-transform-runtime and including them in your babelrc -- See here .

There's another issue with this block of code as well. The async function does not return a promise that can be resolved. Any subsequent function chained to the async function will be executed immediately rendering the async/await useless. Maybe this was 100% example code, but thought it was worth mentioning.

async function fillFilesData() {
            let deferred = $q.defer();
            if (uploader.queue.length) {
                uploader.queue.forEach(function (item) {
                    var reader = new FileReader();
                    reader.onloadend = function (e) {
                        console.log("about to encode");
                        var encoded_file = btoa(e.target.result.toString());
                        $scope.newAnnouncement.files.push({ fileName: item.file.name, encodedDatta: encoded_file });
                    };
                    reader.readAsBinaryString(item._file);

                });

             deferred.resolve(/*something*/);
            }else{
                deferred.resolve(/*whatever*/);
            }
            return deferred.promise;

}
$scope.add = function () {
            let res = await fillFilesData();
    yourFunctionToWait(res);
}
)};
查看更多
登录 后发表回答