如何解决如何在不等待的情况下获得活动的结果?以事件驱动的方式
团队,我对并行调用活动有疑问。
我知道可以使用 const request = require('request');
async function download(url,location) {
try {
const fileStream = fs.createWriteStream(location);
await new Promise((resolve,reject) => {
const res = request(url);
res.on('data',function(chunk) {
// instead of loading the file into memory
// after the download,we can just pipe
// the data as it's being downloaded
fileStream.write(chunk);
});
res.on('end',function() {
resolve();
});
});
return
} catch (e) {
console.log("Err on download files ",e)
}
}
并行调用活动。
对于我的用例,我想在收到所有活动的结果后并行调用 n 个活动,我想转到下一个状态,可以是另一个活动,也可以是决策任务。
但是这里它给了我一个类似于 Java 中的 Future 的 Promise 对象。如果我们编写 promise.get() 来获取结果,但它阻塞了线程。
我需要类似于事件驱动方式的东西,而不阻塞线程。
希望你明白我的问题!!
解决方法
您不必使用 .get()
。
在Promise中,可以注册一个回调函数,当结果可用或返回错误时调用。
您可以根据需要使用以下其中一种:
- 然后申请
- 处理
- 然后撰写
- 异常
这种风格类似于 Java 的 CompletableFuture。
/**
* Returns Promise that contains a result of a function. The function is called with the value of
* this Promise when it is ready. #completeExceptionally is propagated directly to the returned
* Promise skipping the function.
*
* <p>Note that no blocking calls are allowed inside of the function.
*/
<U> Promise<U> thenApply(Functions.Func1<? super V,? extends U> fn);
/**
* Returns Promise that contains a result of a function. The function is called with the value of
* this Promise or with an exception when it is completed. If the function throws a {@link
* RuntimeException} it fails the resulting promise.
*
* <p>Note that no blocking calls are allowed inside of the function.
*/
<U> Promise<U> handle(Functions.Func2<? super V,RuntimeException,? extends U> fn);
/**
* Returns a new Promise that,when this promise completes normally,is executed with this promise
* as the argument to the supplied function.
*
* @param fn the function returning a new Promise
* @param <U> the type of the returned CompletionStage's result
* @return the Promise that completes when fn returned Promise completes.
*/
<U> Promise<U> thenCompose(Functions.Func1<? super V,? extends Promise<U>> fn);
/**
* Returns a new Promise that,when this promise completes exceptionally,is executed with this
* promise's exception as the argument to the supplied function. Otherwise,if this promise
* completes normally,then the returned promise also completes normally with the same value.
*
* @param fn the function to use to compute the value of the returned CompletionPromise if this
* CompletionPromise completed exceptionally
* @return the new Promise
*/
Promise<V> exceptionally(Functions.Func1<Throwable,? extends V> fn);
,
添加到伟大的 Long 的答案中。
您可以使用 Promise.anyOf
以阻塞方式等待集合中的单个 Promise 完成。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。