gpt4 book ai didi

javascript - 如何使用 Promise 对一系列动态生成的异步操作进行排序?

转载 作者:行者123 更新时间:2023-12-03 04:36:48 26 4
gpt4 key购买 nike

在下面的示例中,我模拟了一个场景,其中用户可以触发一些操作,每个操作都是一个异步操作(包装在 promise 中),可以通过随机计时来解决。

操作列表也是动态的,用户在一段时间内只能触发一个或多个操作。

我需要:

  • 保持 promise 解决方案的顺序,并考虑到提前不知道完整的操作列表。

我可以使用 ES6 和浏览器原生 Promises

要测试该示例,请多次单击该按钮(以不同的频率)。

  (function (window) {
document.addEventListener('DOMContentLoaded', e => {
let logActionsElm = document.getElementById('logActions');
let logOperationsElm = document.getElementById('logOperations');
let logCounterElm = document.getElementById('logCounter');
let btnActionElm = document.getElementById('btnAction');

let actionCounter = 0;

let operationDurations = [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000];
let getRandomNumber = (min, max) => Math.floor(Math.random() * (max - 0 + min)) + min;
let getRandomOperationDuration = x => operationDurations[getRandomNumber(0, 8)];

let promises = [];

let createAction = (id, duration) => {

logActionsElm.innerHTML += `${id} action_start_duration: ${duration} --------- ${id}<br>`;

let promiseAction = new Promise((resolve, reject) => {
setTimeout(e => {
logActionsElm.innerHTML += `${id} action_end___duration: ${duration} --------- ${id}<br>`;
}, duration);
});
};

let createOperation = x => {
actionCounter++;
let duration = getRandomOperationDuration() / 10;
createAction(actionCounter, duration);
//logActionsElm.innerHTML += `action ${actionCounter} created will resolve after ${duration}<br>`;
};

btnActionElm.addEventListener('click', e => {
createOperation();
});

var counter = 0;
setInterval(x => {
if (counter >= 20) {
return;
}
counter++;
logCounterElm.innerHTML += `${counter} second <br>`;
}, 1000);
});
})(window);
        body {
font-size: 1.5em;
font-family: 'Courier New';
}

#logCounter {
position: fixed;
top: 0;
right: 0;
margin: 2em;
}
    <button id="btnAction">Triger and action</button>
<div id="logActions"></div>
<div id="logOperations"></div>
<div id="logCounter"></div>

最佳答案

您可以将新的操作函数附加到单个 promise 中,以确保在所有先前的操作都已解决之前不会评估操作:

let queue = Promise.resolve();
let userActionIdCounter = 0;

function queueAction(fn) {
queue = queue.then(fn);
return queue;
}

function userAction() {
return new Promise((resolve) => {
const seconds = Math.ceil(Math.random() * 5);
const actionId = userActionIdCounter;
userActionIdCounter += 1;
console.log('User action', userActionIdCounter, 'started');
setTimeout(() => {
console.log('User action', userActionIdCounter, 'complete');
resolve();
}, seconds * 1000);
});
}

document.getElementById('action').addEventListener('click', () => {
queueAction(userAction);
});
<button id='action'>Trigger action</button>

关于javascript - 如何使用 Promise 对一系列动态生成的异步操作进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com