简体   繁体   English

Promise.all()并了解它何时结算

[英]Promise.all() and understanding when it resolves

I'm newer to node.js and writing a program that is going to require promises for async API calls. 我是node.js的新手,并编写了一个需要承诺异步API调用的程序。 I have a question regarding the execution of some example code that I have stumbled across in my research. 关于我在研究中偶然发现的一些示例代码的执行,我有一个问题。

The code below (from my understanding) will hit an API, wait for the response, then resolve that response as a promise. 下面的代码(根据我的理解)将命中一个API,等待响应,然后将该响应解析为一个承诺。 This is done iteratively and every created promise is passed into an array of promises. 这是迭代完成的,每个创建的promise都会传递给promises数组。 Eventually Promise.all() is called on the array of promises and .then() more code will execute to iterate over the array and add the image to the page. 最终Promise.all()在promises数组上调用.then()将执行更多代码迭代数组并将图像添加到页面。

function getMovie(title) {
  return new Promise(function(resolve, reject) {
  var request = new XMLHttpRequest();

  request.open('GET', 'http://mymovieapi.com/?q=' + title);
  request.onload = function() {
    if (request.status == 200) {
    resolve(request.response); // we get the data here, so resolve the Promise
    } else {
      reject(Error(request.statusText)); // if status is not 200 OK, reject.
    }
  };

    request.onerror = function() {
      reject(Error("Error fetching data.")); // error occurred, so reject the Promise
    };

    request.send(); // send the request
 });
}

function fetchMovies() {
  var titles = document.getElementById('titles').value.split(',');
  var promises = [];

  for (var i in titles) {
    promises.push(getMovie(titles[i])); // push the Promises to our array
  }

  Promise.all(promises).then(function(dataArr) {
    dataArr.forEach(function(data) {
    var img = JSON.parse(data)[0].poster.imdb;

    document.getElementById('movies').innerHTML =      document.getElementById('movies').innerHTML + '<img src="' + img + '"/>';
    });
  }).catch(function(err) {
    console.log(err);
  });
};
fetchMovies();

What I'm not understanding here is how Promise.all() waits for ALL of the API responses to be pushed into promises. 我在这里不理解的是Promise.all()如何等待所有API响应被推送到promises中。 Since getMovie(title) resolves every promise before it is pushed into the promises array, shouldn't it be the case that the first resolved promised that is pushed in causes the Promise.all() section to execute (as 1 of 1 promises in the array are resolved)? 由于getMovie(title)在推送到promises数组之前解析了每个promise,因此不应该是推入的第一个已解决的promise会导致Promise.all()部分执行(作为1中的1个承诺)数组已解决)?

I think the confusion comes where you say "Since getMovie(title) resolves every promise before it is pushed into the promises array". 我认为混淆来自于你说“因为getMovie(title)在将其推入promises数组之前解析了所有的promises ”。

This is not what is happening. 这不是正在发生的事情。 Notice the return statement. 注意return语句。 The getMovie function returns a Promise object immediately, and resolves when the resolve (or reject) function is called at some later time (typically), in this case after an asynchronous call. getMovie函数立即返回一个Promise对象,并在稍后(通常)调用resolve(或reject)函数时解析,在这种情况下是异步调用之后。

So it first returns a promise, then at a later time the promise resolves (or rejects). 所以它首先返回一个promise,然后在promise后解析(或拒绝)。 And Promise.all waits for an array of these promises to resolve. 并且Promise.all等待一系列这些承诺来解决。

By the time you call Promise.all , the array has been filled with the Promise objects. 当你调用Promise.all ,数组已经填充了Promise对象。 Promise.all does the equivalent of calling .then on all of the promises. Promise.all确实调用等效.then对所有的承诺。 When all of the promises are resolved, or one rejects, your handlers get called. 当所有承诺都得到解决或者拒绝承诺时,您的处理程序就会被调用。

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

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