简体   繁体   中英

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.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:

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.

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).

You can do that using Promise.all (using TypeScript syntax): https://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. Then use Promise.All to handle the success or failure of them all.

See this Fiddle for an example of Promise.all:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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