[英]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 與GetInitialData
的 10 個實例組合到GetStudentName
中的數組中,類似於以下?
Promise.All([GetInitialData + IDs.map(Id => GetStudentName(Id)]);
你在正確的道路上:
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>
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.