gpt4 book ai didi

javascript - Promise 回调队列对某些回调具有优先级

转载 作者:行者123 更新时间:2023-12-01 00:34:28 24 4
gpt4 key购买 nike

我的代码需要同时执行多个异步操作,并以特定的顺序方式处理它们的 promise 。

我所说的“特定顺序方式”是什么意思==>假设你正在开始 promise promise1 , promise2 , promise3按照这个顺序,promise3 实际上首先解析,promise2 其次,那么我想要的是处理 promise3 , promise2promise1按此顺序依次

让我们考虑一个timeout X 秒后超时的异步函数,以及 fetchMyItem1 , fetchMyItem2 ,该返回 promise 在满足时应执行不同的代码,具体取决于是否 timeout是否已解决。

对于一个具体的场景,假设有一位顾客在柜台等待送货,要么顾客留下来,我们可以一次带一件商品直接在柜台为他服务,要么顾客离开离开( timeout ),我们必须请服务员过来,以便当元素到达时,他/她可以将元素带给他。请注意,即使一件商品正在交付,其他​​商品也应该仍在交付中( promise 待定),甚至可能在为客户提供一件商品或服务器到达时到达(履行)。

这是一些开始的代码

const allItemsToBeDeliveredPromises = [fetchMyItem1(), fetchMyItem2(), ...]
const customerLeavesCounterPromise = timeout()

const waiter = undefined

const allPromisesToBeFulfilled = [...allItemsToBeDeliveredPromises, customerLeavesCounterPromise]

// LOOP
const itemDeliveredOrVisitorLeft = await Promise.all(allPromisesToBeFulfilled)

if hasCustomerLeft(itemDeliveredOrCustomerLeft) {
// hasCustomerLeft allows us to detect if the promise that resolved first is `customerLeavesCounterPromise` or not
waiter = await callWaiter()
} else {
// An item has arrived
if (waiter) {
deliverItemViaWaiter(itemDeliveredOrVisitorLeft)
} else {
deliverItemAtCounter(itemDeliveredOrVisitorLeft)
}
}
// remove itemDeliveredOrCustomerLeft from allPromisesToBeFulfilled

// END loop

我不确定如何针对这种情况实现循环。 Promise 必须在解析时累积到队列中,但队列中特定的 Promise 是有优先级的(超时的 Promise 应该在到达时尽快执行,但如果 Promise 已经履行完毕,则在处理完当前 Promise 后执行)正在处理)

最佳答案

My code needs to perform a multitude of async actions simultaneously and handle their promises in a specific sequential way.

您可以使用流来使用 Promise,因为流本质上是一次处理一条消息的队列。

想法(即未经测试):

import { Readable, Writable } from 'stream';
let customerHasLeft = false;
/*const customerLeavesCounterPromise = */timeout() // your code...
.then(() => { customerHasLeft = true; }); // ... made boolean
// let's push all our promises in a readable stream
// (they are supposedly sorted in the array)
const input = new Readable({
objectMode: true,
read: function () { // don't use arrow function: we need `this`
const allItemsToBeDeliveredPromises = [fetchMyItem1(), fetchMyItem2(), ...]; // your code
// put everything, in the same order, in the output queue
allItemsToBeDeliveredPromises.forEach(p => this.push(p));
this.push(null); // terminate the stream after all these
}
});
// let's declare the logic to process each promise
// (depending on `timeout()` being done)
const consumer = new Writable({
write: async function (promise, uselessEncoding, callback) {
try {
const order = await promise; // wait for the current promise to be completed
} catch (e) {
/* delivery error, do something cool like a $5 coupon */
return callback(e); // or return callback() without e if you don't want to crash the pipe
}
if (customerHasLeft) { /* find a waiter (you can still `await`) and deliver `order` */ }
else { /* deliver `order` at the counter */ }
callback(); // tell the underlying queue we can process the next promise now
}
});
// launch the whole pipe
input.pipe(consumer);
// you can add listeners on all events you'd like:
// 'error', 'close', 'data', whatever...

编辑:实际上我们希望在 promise 解决时处理它们,但要按顺序进行(即对所有 promise 进行单个后处理)

let customerHasLeft = false;
timeout() // your code...
.then(() => { customerHasLeft = true; }); // ... made boolean
const allItemsToBeDeliveredPromises = [fetchMyItem1(), fetchMyItem2(), ...];
const postProcessChain = Promise.resolve(); // start with a promise ready to be thened
// add a next step to each promise so that as soon as one resolves, it registers
// as a next step to the post-process chain
allItemsToBeDeliveredPromises.forEach(p => p.then(order => postProcessChain.then(async () => {
// do something potentially async with the resulting order, like this:
if (customerHasLeft) { /* find a waiter (you can still `await`) and deliver `order` */ }
else { /* deliver `order` at the counter */ }
})));

关于javascript - Promise 回调队列对某些回调具有优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58247385/

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