JavaScript ES6-如何在Promise.All中组合promise方法?

问题描述 投票:1回答:2

[我有两个promise方法,第一个是GetInitialData,它只能运行一次,还有一个10个id的Int数组,称为ids,第二个方法GetStudentName,将在每个学生id上执行。现在,我想在Promise中组合所有11种方法(方法1 + 10 *方法2)。所有,我该如何编写将GetInitialDataGetStudentName的10个实例组合到Promise中的数组中的代码。全部,如下所示?

Promise.All([GetInitialData + IDs.map(Id => GetStudentName(Id)]);
javascript arrays promise es6-promise
2个回答
1
投票

您在正确的道路上:

Promise.all([
  getInitialData,
  // you need to spread this one as it is an array of promises:
  ...ids.map(id => getStudentName(id),
]);

这里是一个演示:所有异步函数都替换为在随机时间内解析的Promise

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>

-1
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.