简体   繁体   English

Angular JavaScript中的异步调用

[英]Async Call in angular javascript

I am trying to read async from a file angularJs. 我正在尝试从angularJs文件读取异步信息。 Having a horrible time trying to make the variable mySuperFile available outside of the callback. 有一个可怕的时间试图使可用的回调以外的变量mySuperFile。 Please see code below. 请参见下面的代码。

fs.readFile('myfile','utf8', function (err, data){
    var mySuperFile = JSON.parse(data);
});

//I want mySuperFile available HERE

Because readFile is asynchronous, everything that uses this must also be asynchronous. 因为readFile是异步的,所以使用它的所有内容也必须是异步的。

Here is an approach: 这是一种方法:

var fetchMySuperFile = new Promise(function(resolve, reject) {
   fs.readFile('myfile','utf8', function (err, data){
       resolve(JSON.parse(data));
   });
};

fetchMySuperFile.then(function(mySuperFile) {
   // OK, you have it now.
});

This can still be useful. 这仍然有用。 The nature of javascript promises is you can invoke fetchMySuperFile.then multiple times, but it will still have only called readFile one time. JavaScript fetchMySuperFile.then的性质是您可以多次调用fetchMySuperFile.then ,但它一次只会调用readFile

Of course, since it's angular, you might want to use $q instead of Promise . 当然,由于它是有角度的,因此您可能要使用$q代替Promise The reason why is that, after a $q has resolved, angular refreshes. 原因是在$q解决后,角度刷新。 (You won't need to invoke $scope.$apply() ) (您无需调用$scope.$apply()

Due to async nature of js, you can't do something like this: 由于js的异步特性,您无法执行以下操作:

var mySuperFile;
fs.readFile('myfile','utf8', function (err, data){
    mySuperFile = JSON.parse(data);
});
console.log(mySuperFile);

This is because the line console.log( mySuperFile ); 这是因为console.log(mySuperFile); won't wait until the function above finished. 等到上面的功能完成后再说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM