Promise.all不能按预期工作

时间:2018-07-04 01:13:22

标签: javascript typescript promise synchronization

我有几个异步调用要在最终调用之前执行,并且我有与此stackoverflow answer类似的方法。

这是Codepen

中的代码
class Person {
  name: string;
  constructor(init){
    this.name = init;
  }
}
let people: Person[] = [];
let names:string[] = ['janes','james','jo','john','josh'];
names.forEach(n=>people.push(new Person(n)));
function printName(name:string) {
  let getSomething = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(name);  
    },1000)
  });
  getSomething.then(function(){
    console.log(name);
  });
}
/// main
let request = [];
console.log('start');
people.forEach(person => { 
  request.push(printName(person.name));
})
Promise.all(request).then(result=> {
  console.log(result);
  console.log("finsh");
})

上面的代码产生了什么:

"start"
[undefined, undefined, undefined, undefined, undefined]
"finsh"
"janes"
"james"
"jo"
"john"
"josh"

而我期望的是

"start"
"janes"
"james"
"jo"
"john"
"josh"
[undefined, undefined, undefined, undefined, undefined]
"finsh"

1 个答案:

答案 0 :(得分:4)

您没有将在printName中创建的承诺返回给request数组,因此Promise.allundefined s数组中被调用(并且,作为结果,立即解决)。链接并返回诺言。

通常,当您使用Promise.all时,您会希望解析的数组包含值而不是undefined s-为此,还请在{内返回name {1}},以便getSomething.then将使用名称数组进行解析:

Promise.all

使用普通Javascript的工作片段:

function printName(name:string) {
  let getSomething = new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(name);  
    },1000)
  });
  return getSomething.then(function(){
    console.log(name);
    return name; // add this line too
  });
}