JavaScript ES6 - 如何在 Promise.All 中组合 promise 方法?
JavaScript ES6 - How to combine promise methods in Promise.All?
我有两个 promise 方法,第一个是 GetInitialData
,它只会 运行 一次,还有一个名为 ids
的 10 id 的 Int 数组,第二个方法是 GetStudentName
这将在每个学生 ID 上执行。现在我想在 Promise.All 中组合所有 11 种方法(方法 1 + 10 * 方法 2),我该如何编写将 GetInitialData
与 GetStudentName
的 10 个实例组合的代码进入 Promise.All 内的数组,如下所示?
Promise.All([GetInitialData + IDs.map(Id => GetStudentName(Id)]);
const getOne = async () => 1;
const getTwo = async () => 2;
(async () => {
const [one, two] = await Promise.all([getOne(), getTwo()]);
console.log(one);
console.log(two);
})().then(undefined);
// 1
// 2
你走在正确的道路上:
Promise.all([
getInitialData,
// you need to spread this one as it is an array of promises:
...ids.map(id => getStudentName(id),
]);
这是一个演示:
所有异步函数都替换为在随机时间内解决的承诺
const fnPromise = () => new Promise((resolve, reject) =>
setTimeout(() => resolve(), Math.round(Math.random() * 1000))
);
let i = 0;
async function getInitialData() {
await fnPromise();
return i++;
}
async function getStudentName() {
await fnPromise();
return i++;
}
const ids = [1, 2, 3, 4, 5, 6];
async function init() {
$("#console").html('Please wait...');
const allResolved = await Promise.all([
getInitialData(),
...ids.map(() => getStudentName()),
]);
// console.log(JSON.stringify(allResolved, null, 2))
$("#console").html(`[${allResolved.join(', ')}]`)
}
init()
body {
background: #333;
color: #fff;
font-size:2rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id='console'></pre>
我有两个 promise 方法,第一个是 GetInitialData
,它只会 运行 一次,还有一个名为 ids
的 10 id 的 Int 数组,第二个方法是 GetStudentName
这将在每个学生 ID 上执行。现在我想在 Promise.All 中组合所有 11 种方法(方法 1 + 10 * 方法 2),我该如何编写将 GetInitialData
与 GetStudentName
的 10 个实例组合的代码进入 Promise.All 内的数组,如下所示?
Promise.All([GetInitialData + IDs.map(Id => GetStudentName(Id)]);
const getOne = async () => 1;
const getTwo = async () => 2;
(async () => {
const [one, two] = await Promise.all([getOne(), getTwo()]);
console.log(one);
console.log(two);
})().then(undefined);
// 1
// 2
你走在正确的道路上:
Promise.all([
getInitialData,
// you need to spread this one as it is an array of promises:
...ids.map(id => getStudentName(id),
]);
这是一个演示:
所有异步函数都替换为在随机时间内解决的承诺
const fnPromise = () => new Promise((resolve, reject) =>
setTimeout(() => resolve(), Math.round(Math.random() * 1000))
);
let i = 0;
async function getInitialData() {
await fnPromise();
return i++;
}
async function getStudentName() {
await fnPromise();
return i++;
}
const ids = [1, 2, 3, 4, 5, 6];
async function init() {
$("#console").html('Please wait...');
const allResolved = await Promise.all([
getInitialData(),
...ids.map(() => getStudentName()),
]);
// console.log(JSON.stringify(allResolved, null, 2))
$("#console").html(`[${allResolved.join(', ')}]`)
}
init()
body {
background: #333;
color: #fff;
font-size:2rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id='console'></pre>