【发布时间】:2015-09-19 10:15:02
【问题描述】:
我已阅读:Promise - JavaScript | MDN 并在此处查看了本书中有关承诺的部分:Eloquent Javascript 以及其他谷歌搜索,但我似乎无法确定这是否是一个问题,因为我对 Promises 的理解或图书馆的混合物。我想要完成的是发出请求,检索响应,然后使用该响应发出另一个请求。我想我可以使用以下正常模式:
promiseObj.get('url')
.then(function(response){
//do something with response
var name = response.name;
return name;
})
.then(function(name){
//do something with name
}
但是有些东西不能正常工作。我正在尝试使用两个不同的 promise 对象来发出请求。我必须使用 podio API 发出请求,检索信息,然后使用 AngularJS $http 承诺。这是我的代码:
podio.request('get','/item/' + eventId).then(function(responseEvent) {
...
var imgId = responseEvent.img_id;
...
return imgId;
}).then(function(imgId){
console.log(imgId);
var config = { responseType: 'arraybuffer'};
$http.get('https://api.podio.com/file/' + imgId + '/raw',config)
.then(function(response) {
console.log('hi 2');
var arr = new Uint8Array(response.data);
var raw = String.fromCharCode.apply(null,arr);
var b64 = btoa(raw);
var dataURL = "data:image/jpeg;base64,"+b64;
$scope.event.img.src = dataURL;
},function(error){
console.log(error);
});
});
在我的第二个 then 中,我可以在控制台中看到 imgId,但之后没有任何反应。我可能会错过什么。
【问题讨论】:
-
imgId不是承诺吗? -
@MichaelPerrenoud 从传递给
.then的函数返回的任何值都被包装在一个Promise 中。
标签: javascript angularjs promise angular-promise