【问题标题】:JavaScript ES6 - How to combine promise methods in Promise.All?JavaScript ES6 - 如何在 Promise.All 中组合 Promise 方法?
【发布时间】:2020-05-01 03:28:42
【问题描述】:

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

Promise.All([GetInitialData + IDs.map(Id => GetStudentName(Id)]);

【问题讨论】:

  • 不清楚GetInitialData()GetStudentName(Id) 返回什么,这里IDs 是什么?请在主帖中添加完整的详细信息。
  • Promise.All(GetInitialData(), ...IDs.map(Id => GetStudentName(Id));?我发现很难理解你到底在追求什么,所以这主要是一个猜测。
  • 你需要Promise.All([GetInitialData(), ...IDs.map(GetStudentName)]);
  • 是的,我需要一种方法将通过 IDs.map 调用的方法 1 和方法 2 组合到 Promise.All 中的新数组中,这里显示了一些东西@AZ_

标签: javascript arrays promise es6-promise


【解决方案1】:

你在正确的道路上:

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>

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    • 虽然此代码可能提供问题的解决方案,但强烈建议您提供有关此代码为何和/或如何回答问题的附加上下文。从长远来看,只有代码的答案通常会变得毫无用处,因为未来遇到类似问题的观众无法理解解决方案背后的原因。
    猜你喜欢
    • 1970-01-01
    • 2016-06-21
    • 2016-03-20
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    相关资源
    最近更新 更多