如何等到从 ES6 代理完成对 return 的回调

How to wait until a callback is finished to return from ES6 Proxy

我不能使用 promises,因为它会强制用户将所有内容都转换为同步方法的异步函数。有什么方法可以强制代理在回调完成之前不 return?

function callbackCase() {
    function saySomething(callback) {
        callback("Whosebug");
    }

    console.error = new Proxy(console.error, {
        apply: (target, thisArg, args) => {
            saySomething((result) => {
                return result;
            })
        }
    })

    let test = console.error();

    console.log("From Callback Case", test);
}




function nonCallbackCase() {
    console.errors = new Proxy(console.error, {
        apply: (target, thisArg, args) => {
            return "Whosebug";
        }
    })

    let test = console.errors();

    console.log("From Non Callback Case", test);
}


callbackCase()
nonCallbackCase()

Is there any way to force the proxy to not to return until the callback complete?

不,没有。 Javascript 中无法将异步操作变成同步操作。您尝试做的任何事情(例如在标志上循环)只会阻塞事件循环,从而阻止您的异步操作完成,因此您将陷入僵局。

可通过三种基本方式来传回异步操作的结果或完成、回调、承诺或事件。您将需要使用其中一种机制。

换句话说,您不能将异步操作压缩为同步操作 API。您必须将 API 更改为异步 API。返回与异步操作相关的承诺是 Javascript 中执行此操作的现代方法。这让调用者可以使用 .then()await 来监视操作的完成和结果。