我使用以下代码预加载图像:
function preLoad() {
var deferred = $q.defer();
var imageArray = [];
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = $scope.abbreviations[i].imgPath;
}
imageArray.forEach.onload = function () {
deferred.resolve();
console.log('Resolved');
}
imageArray.forEach.onerror = function () {
deferred.reject();
console.log('Rejected')
}
return deferred.promise;
}
preLoad();
Run Code Online (Sandbox Code Playgroud)
我认为图像都正确加载,因为我可以看到“已解决”日志。
后来有人指出,上面的代码并不能保证在解决承诺之前加载所有图像。事实上,只有第一个承诺被解决了。
我被建议改用$q.all应用于一系列承诺。这是结果代码:
function preLoad() {
var imageArray = [];
var promises;
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = …Run Code Online (Sandbox Code Playgroud) 此刻,我对承诺有点头脑风暴。
鉴于以下代码:
$scope.getData = function(user) {
return $http.post('/endpoint', "some post data", { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
.success(function (response) {
var myThing = { stuff: response.infoData };
localStorageService.set('myData', { stuff: response.infoData });
return myThing;
});
};
Run Code Online (Sandbox Code Playgroud)
是从成功回调返回的myThing对象:
据我了解:
这样对吗?是否有我遗漏的东西,在成功方法中返回对象有什么好处,还是返回是多余的?(我很清楚这是可以改进的代码,但我试图具体找出为什么有人会写这个,或者这完全是一个错误)
我定义了一个函数如下:
function getCurrentComponent(){
if($rootRouter._currentInstruction){
return $rootRouter.recognize($rootRouter._currentInstruction.urlPath).then(function (data) {
return data.component.componentType;
});
}else{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
为了调用这个函数,我做了如下操作:
factory.getCurrentComponent().then(function (data) {
...
});
Run Code Online (Sandbox Code Playgroud)
问题是当getCurrentComponent函数返回空值时,会生成以下错误:
无法读取 null 的属性“then”
我该如何解决这个问题?
我忘了说我仅限于使用 ES5,所以我无法使用该对象Promise
我正在尝试做一个 ngIf ,其结果取决于承诺。
模板
<div>
<select [(ngModel)]="carValue" name="carName">
<option value="renault">Renault</option>
<option value="bmw">Bmw</option>
</select>
<p *ngIf="isDisplayed()">Good choice!</p>
</div>
Run Code Online (Sandbox Code Playgroud)
到目前为止,函数 isDisplayed 是
isDisplayed() {
return this.carValue === 'bmw';
}
Run Code Online (Sandbox Code Playgroud)
但我希望它是异步的。就像是
isDisplayed() {
return this.getBestChoice().then((result) => result);
}
getBestChoice() {
// fake http call
return new Promise((resolve) => {
setTimeout(() => resolve('bmw'), 3000);
});
}
Run Code Online (Sandbox Code Playgroud)
显然这是行不通的。我有如何实现这个的想法,但不确定它是否干净。
这是一个朋克。
嘿家伙我正在将一些数据发布到服务器然后基于几个变量再次发布到循环内的不同URL.
到目前为止我用的是一个例子:
$scope.items = [{'name':'Test1','hasd':1,'hase':1},{'name':'Test2','hasd':0,'hase':1}];
var promises = [];
angular.forEach($scope.items,function(obj) {
promises.push($http({
type:'post',
url:'test',
data:obj
}).then(function(response) {
if(response.status==201) {
//do another http call
if(obj.hasd==1) {
$http({}).then(function() {
var something=1;
});
}
}
}));
$q.all(promises).then(function(){
alert('done');
});
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,它只是查看最初的$ http呼叫的承诺,而不是任何内部呼叫.有没有办法将所有$ http调用添加到循环内的promise中?
干杯,本
我有一系列的承诺,依赖于另一个完成,并希望"然后"他们在一起得到一个代表整个序列完成的承诺.这似乎工作正常,但我似乎没有任何失败级联下来的承诺链,因为它似乎应该从文档中做,这是一个代码示例,以说明我正在努力的:
var deferred = $q.defer();
deferred.resolve();
var resolvedPromise = deferred.promise;
var rejectedPromise = $q.reject('rejected');
var aPromise = resolvedPromise.then(rejectedPromise);
aPromise.then(function () {
console.log('promise fulfilled');
}, function () {
console.log('promise rejected');
});
Run Code Online (Sandbox Code Playgroud)
我希望记录"承诺拒绝",但我得到"承诺履行".我有什么想法可以实现我想要的行为?
我正在尝试为服务设置测试工具,使前端大约需要1秒钟才能播放一些东西。
我正在使用aq,所以我可以在控制器中调用.then,所以我发疯了,现在可以通过使用set timeout来伪造它,但是我认为我的语法不正确。这是我尝试过的:
return $q(function(resolve, reject) {
setTimeout(function() {
}, 1000).then(resolve);
});
Run Code Online (Sandbox Code Playgroud)
我只希望它等待一秒钟然后解决。对此新手,将不胜感激任何意见,谢谢!
使用$ q服务和Angular,我编写了一个异步获取数据的函数。下面的示例有点简化,但与我的生产代码类似:
DataService.fetchData(1)
.then(function (data1) {
this.data1 = data;
DataService.fetchData(2)
.then(function (data2) {
this.data2 = data2;
DataService.fetchData(3)
.then(function (data3) {
this.data3 = data3;
doSomething(this.data1, this.data2, this.data3);
}, function () {
alert("failure getting data 3");
})
}, function () {
alert("failure getting data 2");
});
}, function () {
alert("failure getting data 1");
});
Run Code Online (Sandbox Code Playgroud)
假设我需要进行三个异步函数调用来获取数据,如上所述。然后,数据将通过角度视图显示。
但是,以上代码非常有缺陷。很难阅读,并且函数调用是深层嵌套的。我想写一些类似的东西,这将使三个异步函数调用并仅在所有三个函数都完成之后才执行某个函数来处理数据,并且在发生错误的情况下,应该只有一个错误处理程序函数。
还应注意,函数将返回异步数据的顺序是未知的。
如何在Angular中做到这一点?
我有一个返回标准解决方案或拒绝承诺的服务.在我的控制器中,我目前有类似的东西:
myService.myServiceFunction(id).then(function(data){
// do something with data
$scope.myServiceFunctionFinished = true;
}, function(data){
// do some error handling with data
$scope.myServiceFunctionFinished = true;
});
Run Code Online (Sandbox Code Playgroud)
在上文中,错误和成功响应都将触发$scope.myServiceFunctionFinished分配true值.
反正是否有上述速记,所以我没有两次定义相同的东西?如果上面的代码是try catch语句,我正在寻找相当于finally块.我在上面显示的变量赋值必须在服务器响应后发生.
我是Angular2的新手,我试图从json文件中获取数据.要做到这一点,我使用Http with Promise,但是当我从我的promise变量中执行console.log时,它们返回Undefined.
post.services.ts
import {Injectable} from '@angular/core';
import { Headers, Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import {Post} from '../interfaces/post.interface';
@Injectable()
export class PostService{
private url = 'myjson.json';
constructor(private http: Http){ }
private extractData(res: Response) {
let body = res.json();
console.log(body.data);
return body.data || null;
}
getPosts(): Promise<Post[]>{
return this.http.get(this.url)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
Run Code Online (Sandbox Code Playgroud)
posts.component.js
import { Component, OnInit } from …Run Code Online (Sandbox Code Playgroud) angular-promise ×10
angularjs ×9
javascript ×5
promise ×4
angular ×2
asynchronous ×2
ecmascript-5 ×1