使用香草承诺的 RSVP 哈希
RSVP hash using vanilla promises
RSVP lib has a hash of promises 允许 "retrieve" 承诺引用的助手:
var promises = {
posts: getJSON("/posts.json"),
users: getJSON("/users.json")
};
RSVP.hash(promises).then(function(results) {
console.log(results.users) // print the users.json results
console.log(results.posts) // print the posts.json results
});
有没有办法用普通的 promises 做这样的事情(在现代 ES 中)?
开箱即用?不,只有 Promise.all
,但它接受数组,而不是字典。但是您可以创建一个辅助函数,它接受承诺字典,转换为数组,在其上运行 Promise.all
,然后再用一个 then
处理它,将结果数组转换回字典。
实现起来并不难。
async function hash(promiseObj) {
// Deconstitute promiseObj to keys and promises
const keys = [];
const promises = [];
Object.keys(promiseObj).forEach(k => {
keys.push(k);
promises.push(promiseObj[k]);
});
// Wait for all promises
const resolutions = await Promise.all(promises);
// Reconstitute a resolutions object
const result = {};
keys.forEach((key, index) => (result[key] = resolutions[index]));
return result;
}
hash({
foo: Promise.resolve(8),
bar: Promise.resolve(16),
}).then(results => console.log(results));
RSVP lib has a hash of promises 允许 "retrieve" 承诺引用的助手:
var promises = {
posts: getJSON("/posts.json"),
users: getJSON("/users.json")
};
RSVP.hash(promises).then(function(results) {
console.log(results.users) // print the users.json results
console.log(results.posts) // print the posts.json results
});
有没有办法用普通的 promises 做这样的事情(在现代 ES 中)?
开箱即用?不,只有 Promise.all
,但它接受数组,而不是字典。但是您可以创建一个辅助函数,它接受承诺字典,转换为数组,在其上运行 Promise.all
,然后再用一个 then
处理它,将结果数组转换回字典。
实现起来并不难。
async function hash(promiseObj) {
// Deconstitute promiseObj to keys and promises
const keys = [];
const promises = [];
Object.keys(promiseObj).forEach(k => {
keys.push(k);
promises.push(promiseObj[k]);
});
// Wait for all promises
const resolutions = await Promise.all(promises);
// Reconstitute a resolutions object
const result = {};
keys.forEach((key, index) => (result[key] = resolutions[index]));
return result;
}
hash({
foo: Promise.resolve(8),
bar: Promise.resolve(16),
}).then(results => console.log(results));