gpt4 book ai didi

javascript - 从 promise 的 promise 中获取数据以及其他数据 (promise.all)

转载 作者:行者123 更新时间:2023-11-29 17:54:30 24 4
gpt4 key购买 nike

所以我有一些需要解决的 promise ,这样我才能获得数据。当然,我有方便的 promise.all() 可供我使用。不幸的是,其中一个 promise 会返回另一组 promise 。是否有可能实现这些 promise ?

例如:

var result = {};
let pName = getName(); // returns promise<string>
let pAge = getAge(); // returns promise<string>
let pSchools = getSchools; // returns promise<Array<promise<string>>>

return promise.all([pName, pAge, pSchool]).then(function(res) {
result["name"] = res[0];
result["age"] = res[1];
result["schools"] = [];

// This next section I don't think will work because it doesn't resolve "in time".
res[2].map(function(school) {
school().then(theSchool => result["schools"].push(theSchool))
});
return result;
}); // returns promise<{
// "name": "string",
// "age": "string",
// "schools": [string1, ..., stringN]
// }>

有人遇到过这样的事情吗?你是怎么做到的?

最佳答案

您需要返回解析学校的内部 Promise 的结果:

return promise.all([pName, pAge, pSchool]).then(function(res) {
return promise.all(res[2].map(school => school()))
.then(schools => {
result["name"] = res[0];
result["age"] = res[1];
result["schools"] = schools;
return result;
});
}));
});

关于javascript - 从 promise 的 promise 中获取数据以及其他数据 (promise.all),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40530501/

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