gpt4 book ai didi

javascript - 回调和返回值

转载 作者:行者123 更新时间:2023-12-03 12:05:00 25 4
gpt4 key购买 nike

我坚持使用两个外部库并将它们一起使用。一个只有异步接口(interface),另一个需要我从回调返回一个值。

// this function is called as a callback from an external library
// it is required that the function returns a certain value
function onevent()
{
// the callback for the "thirdparty.foo" function
// with the result that must be returned from onevent
function ondone(result) {
// ???
}
// this is a call to a third party library that only has this asynchronous interface
thirdparty.foo(ondone);
// ??? return result;
}

JavaScript 对我来说还很陌生,我无法找到解决这个问题的任何解决方案。

我正在寻找能够在从 onevent 返回之前等待 ondone 完成的东西。与 C++ 类似的是来自 std::future.wait.get

最佳答案

One only has an async interface and the other requires me to return a value from the callback.

如果您必须使用提供异步接口(interface)的接口(interface)来满足不提供异步接口(interface)的接口(interface)的回调,那么这就是一个问题。如果这样做,则根本无法将它们一起使用。没有办法让回调等待异步事件完成而期望回调返回值。

例如:

doSomethingExpectingReturnValueFromCallback(function() {
// You cannot use an asynchronous API here to get the value you return
});

如果同步库理解 Promise(类似于 std::future),那么您可以返回一个 Promise,但听起来不像。

关于javascript - 回调和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25224265/

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