理解承诺中的承诺 Javascript

Understanding Promise within Promise Javascript

我已阅读:Promise - JavaScript | MDN and I reviewed the section on promises in this book here: Eloquent Javascript 以及其他 google 搜索,但我似乎无法确定这是否是一个问题,因为我对 Promises 或混合库的理解。我想要完成的是发出请求,检索响应,然后使用该响应发出另一个请求。我想我可以使用正常模式:

promiseObj.get('url')
.then(function(response){
    //do something with response
    var name = response.name;
    return name;
})
.then(function(name){
    //do something with name
}

但有些地方运行不正常。我正在尝试使用两个不同的承诺对象来发出请求。我必须使用 podio API 发出请求,检索信息,然后使用 AngularJS $http promise。这是我的代码:

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,但之后没有任何反应。我可能遗漏了什么。

如果您想创建两个 promise,请尝试以下方法:

p1.get(function (response) {
  // Work with response here
  return response;
}).then(function (response) {
  return p2.get(response.urlMaybe);
}).then(function (response) {
  // Work on second response
});

大量伪造但可能有一些帮助。

一个原因可能是您没有外部 promise 的错误处理程序,因此如果在 console.log 之后抛出异常,则可能无法检测到错误。我建议您展平您的 Promise 链,以便处理 所有 错误:

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'};
    return $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);
  });

除了 Adrian Lynch 的正确答案之外,假设我们还有一系列请求。每个请求都取决于 所有 先前请求的结果。

promiseFn().then(function(resp) {
    return Promise.all([resp, otherPromiseFn(resp)]);
}).then(function(vals) {
    var first  = vals[0];
    var second = vals[1];
    return Promise.all([first, second, thirdPromiseFn(first, second)]);
});

..等等,聚合值。重要的是,每次你有一个承诺 returning 函数调用你只是 return 承诺,然后你调用 then。请记住,您 return 从您传递给的函数中的所有内容都会自动包装为您 returning 的值的承诺。