简体   繁体   English

JavaScript 中的递归方法调用

[英]Recursive Method Call in JavaScript

I created a wrapper doing httpRequest, returning a Promise to an object and it works for the calls like this:我创建了一个包装器来执行 httpRequest,将一个 Promise 返回给一个对象,它适用于这样的调用:

httpRequest.get("http://some.link/some?query=foo");

or或者

httpRequest.post("http://some.link", {"some":"requestBody"});

And, I need to implement concurrent calls retuning a Promise to an array like:而且,我需要实现并发调用,将 Promise 重新调整为数组,例如:

httpRequest
    .get("http://some.link/some?query=foo")
    .post("http://some.link", {"some":"requestBody"})
    .get("http://another.concurrent/request");

I know how to implement it using promise.all, but it gives bad experience to the user.我知道如何使用 promise.all 来实现它,但它给用户带来了糟糕的体验。

I need to find a way to call the function recurrently like we have in promise.我需要找到一种方法来重复调用该函数,就像我们承诺的那样。

promise.then(res=>foo)
       .then(res=>bar)
       .then(res=>baz)

What you're describing isn't recursion.你所描述的不是递归。

You said you want concurrent HTTP requests that are represented by a single Promise (ie the Promise resolves after all 3 requests complete, in any order).您说您想要由单个Promise表示的并发 HTTP 请求(即Promise在所有 3 个请求完成后以任何顺序解析)。

You can do that using Promise.all (using TypeScript syntax): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all您可以使用Promise.all (使用 TypeScript 语法)做到这Promise.allhttps : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

let req1: Promise<Response> = httpRequest.get( "http://?query=foo" );
let req2: Promise<Response> = httpRequest.post( "http://?query=foo" );
let req3: Promise<Response> = httpRequest.get( "http://?query=foo" );

let reqAll: Promise<Response[]> = return Promise.all( req1, req2, req3 );

let responses: Response[] = await reqAll;

Call all of them, collecting the resulting promises in an array.调用所有这些,将结果 promise 收集到一个数组中。 Then use Promise.All to handle the success or failure of them all.然后使用Promise.All来处理它们的成败。

See this Fiddle for an example of Promise.all:有关 Promise.all 的示例,请参阅此 Fiddle

Promise.all([
    asyncThing(),
    asyncThing(),
    asyncThing()
])
.then((promises) => {
    console.log("all resolved: ", promises)
})
.catch((err) => {
    console.error("first rejection:", err);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM