AngularJS错误:regeneratorRuntime未使用异步函数定义 [英] Angularjs Error: regeneratorRuntime is not defined with async function
问题描述
我正在与angularjs合作,我想执行一些与读取文件数据相关的代码,我想完全执行此功能,然后开始执行另一个代码块.
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未定义
regeneratorRuntime is not defined
这是我的异步函数定义:
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
}
)};
推荐答案
如果babelrc中的目标浏览器/节点版本不支持异步和等待,则它们将被转换为生成器函数或类似它们的东西.没有安装babel-plugin-transform-runtime
插件.有几种解决方法,即安装preset-env
或babel-plugin-transform-runtime
并将其包含在babelrc中-
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 .
此代码块也存在另一个问题.异步功能不会返回可以解决的承诺.链接到异步函数的任何后续函数将立即执行,从而使异步/等待无用.也许这是100%的示例代码,但认为值得一提.
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);
}
)};
这篇关于AngularJS错误:regeneratorRuntime未使用异步函数定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!