gpt4 book ai didi

javascript - Promise.all 没有按预期工作

转载 作者:行者123 更新时间:2023-11-28 14:31:49 26 4
gpt4 key购买 nike

我想在最终调用之前执行一些异步调用,并且我有与此类似的方法 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"

最佳答案

您不会将 printName 中创建的 Promise 返回到 request 数组,因此会在数组上调用 Promise.all 未定义(因此,立即解析)。相反,链接并返回 promise 。

通常,当您使用 Promise.all 时,您希望解析后的数组包含值而不是 未定义 - 为此,也在 getSomething.then 中返回 name,以便 Promise.all 将解析为名称数组:

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
});
}

普通 Javascript 中的工作片段:

class Person {
constructor(init){
this.name = init;
}
}

let people = [];
let names = ['janes','james','jo','john','josh'];
names.forEach(n=>people.push(new Person(n)));

function printName(name) {
let getSomething = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(name);
},1000)
});
return getSomething.then(function(){
console.log(name);
return name;
});
}
let request = [];
console.log('start');
people.forEach(person => {
request.push(printName(person.name));
})
Promise.all(request).then(result=> {
console.log(result);
console.log("finsh");
})

关于javascript - Promise.all 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51164585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com