我有函数
fetchData
接受整数 id
并以随机解析时间调用 Promise
const promise = (ms) => new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Done!');
}, ms);
});
const fetchData= async (id) => {
const ms = Math.floor(Math.random() * 1000);
const ans = await promise(ms);
return ans
}
我有一个
ids = [1, 2, 3, 4, 5]
数组,我需要并行调用 fetchData
与所有 ids
并根据解析所需的时间对 ids
数组重新排序
您需要从函数中返回 2 个参数, 一是真正的答案,二是所花费的时间。
要测量时间,可以使用
performance.now
原生调用。
当您获得这两个元组的结果时,您可以对它们进行排序以处理时间。
我这样做只是为了好玩:
const promise = (ms) => new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Done!');
}, ms);
});
const fetchData = async (id, callback = () => {}) => {
const ms = Math.floor(Math.random() * 1000);
const ans = await promise(ms);
callback(id);
return ans
}
const ids = [1, 2, 3, 4, 5];
const idsInOrder = [];
const callback = id => idsInOrder.push(id);
const promises = ids.map(id => fetchData(id, callback));
Promise.all(promises)
.then(function() {
console.log('ids in order:');
console.log(idsInOrder);
})