简体   繁体   English

这个Promise.all解决方案有什么问题

[英]What is wrong with this Promise.all solution

I need to loop through an array of items and check if each item's type matches desired type. 我需要遍历一组项目,并检查每个项目的类型是否匹配所需的类型。 Once all the checking are done, add the ones that meet requirement to a dropdown select box. 完成所有检查后,将符合要求的检查添加到下拉选择框中。 In an array where 2 items meet the requirement, this code checks is only adding the first item to the dropdown always, what is wrong with it? 在2个项目均满足要求的数组中,此代码检查始终仅将第一项添加到下拉列表中,这有什么问题呢?

var promises = [];
var html = "";

for (var i = 0; i < items.length; i++) {
  var promise = new Promise(function(resolve, reject){
    $.ajax({
      url: "url" + items[i], 
      dataType: "json",
      success: function (data) {
        console.log(data); 
        console.log(data.type); // "mytype"
        console.log(typeof data.type); // string
        if(data.type == "mytype") {
          html += "<option value='" + data.id + "'>" + items[i] + "</option>";
          resolve();
        }
      }
    });
  promises.push(promise); 
  });
}

console.log(promises) // (2) [undefined, Promise]

Promise.all(promises).then(() => {
  $("#dropdownBox").html(html);
});

EDIT: someone pointed out that I need to use each instead of forloop to make a closure, I tried it but still does not work. 编辑:有人指出我需要使用each代替for循环,使封闭,我尝试过,但仍然无法正常工作。 I tried doing 我试着做

$.each(items, function(index){...}

and

items.forEach(function(index){...}

and modified what's inside the loop accordingly but no luck. 并相应地修改了循环中的内容,但没有运气。 This post ( JavaScript closure inside loops – simple practical example ) does not help me. 这篇文章( 循环内的JavaScript封闭-简单的实际示例 )对我没有帮助。

One of the issues you have is not resolving the promise if the type doesn't meet condition. 如果类型不符合条件,您面临的问题之一就是无法兑现承诺。

Your for() loop also doesn't create a closure so i won't be what you expect it to be when request completes 您的for()循环也不会创建闭包,因此当请求完成时, i不会是您期望的闭包

Since $.ajax returns a promise here's a less anti-pattern approach using map() to create closure and the promise array 由于$.ajax返回一个promise,因此这是使用map()创建闭包和promise数组的一种较少反模式的方法

// map array of promises
var promises = items.map((item) => {
  // return $.ajax promise
  return $.ajax({
    url: "url" + item,
    dataType: "json"
  }).then((data) => {
    let html = '';
    if (data.type == "mytype") {
      html += "<option value='" + data.id + "'>" + item + "</option>";
    }
    return html;
  });
});

Promise.all(promises).then((res) => {
  // res is array of  html (or empty) strings returned in each then() above
  $("#dropdownBox").html(res.join(''));
}).catch(err => console.log('At least one request failed'));

Demo 演示版

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

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