稍后将 Promise 存储在 Map 中 resolve/reject

Store Promise in Map to resolve/reject later

我正在 NodeJS 中处理 IPC,希望能够从子进程向父进程发送消息,并 "wait" 获取结果。我的想法是在将唯一消息 ID 映射到承诺的映射中跟踪所有发送的消息。调用 process.on('message`) 后,我通过从父级返回的 ID 查找承诺,并希望解决或拒绝承诺。

我想到了这个,但卡在了 resolve/reject 部分:

'use strict'

import RequestMessage from "../messages/request/RequestMessage";
import ResponseMessage from "../messages/response/ResponseMessage";

const process = require('process');

export class CommunicationManager {
    private messageQueue: Map<string, Promise<any>>;

    constructor() {
        this.messageQueue = new Map();

        process.on('message', (payload: any) => {
            if (payload.hasOwnProperty("_id")
                && this.messageQueue.has(payload.get("_id"))) {

                let promise = this.messageQueue.get(payload);
                // Resolve or reject the promise..

                this.messageQueue.delete(payload.get("_id"));
            } else {
                console.error(`Got unknown message from parent: ${payload}`);
            }
        });
    }

    public execute(message: RequestMessage): Promise<ResponseMessage> {
        process.send(message);
        this.messageQueue.set(message.id(), // a promise here);
    }
}

有人可以在正确的方向上指导我如何解决这个问题吗?这甚至可能和最佳实践吗?

谢谢!

您不会将承诺存储在地图中。您将只存储解析器函数以供稍后调用 - 创建并立即返回承诺。

init() {
    process.on('message', (payload: any) => {
        if ("_id" in payload && this.messageQueue.has(payload._id)) {
            const resolve = this.messageQueue.get(payload._id);
            this.messageQueue.delete(payload._id);
            if (payload.isFulfilled) {
                resolve(payload.value);
            else {
                resolve(Promise.reject(payload.error));
            }
        } else {
            console.error(`Got unknown message from parent: ${payload}`);
        }
    });
}

public execute(message: RequestMessage): Promise<ResponseMessage> {
    return new Promise(resolve => {
        this.messageQueue.set(message.id(), resolve);
        process.send(message);
    });
}

很少在 promise 执行者的其他范围内调用 resolve,但消息传递是其中一种必要且标准的做法。顺便说一句,您可能需要考虑对响应接收设置超时。