---
title: "async with crul"
author: "Scott Chamberlain"
date: "`r Sys.Date()`"
output: 
  html_document:
    toc: true
    toc_float: true
    theme: readable
vignette: >
  %\VignetteIndexEntry{async with crul}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r echo=FALSE}
knitr::opts_chunk$set(
  comment = "#>",
  collapse = TRUE,
  warning = FALSE,
  message = FALSE
)
```

Asynchronous requests with `crul`.

There are two interfaces to asynchronous requests in `crul`:

1. Simple async: any number of URLs, all treated with the same curl options, 
headers, etc., and only one HTTP method type at a time.
2. Varied request async: build any type of request and execute all asynchronously.

The first option takes less thinking, less work, and is good solution when you 
just want to hit a bunch of URLs asynchronously.

The second option is ideal when you want to set curl options/headers on each 
request and/or want to do different types of HTTP methods on each request.

One thing to think about before using async is whether the data provider is 
okay with it. It's possible that a data provider's service may be brought down
if you do too many async requests. 

```{r}
library("crul")
```

## simple async

Build request objcect with 1 or more URLs

```{r echo=FALSE, eval=FALSE}
(cc <- Async$new(
  urls = c(
    'https://www.heroku.com/',
    'http://docs.python-tablib.org/en/latest/',
    'https://httpbin.org'
  )
))
```

```{r}
(cc <- Async$new(
  urls = c(
    'https://httpbin.org/get?a=5',
    'https://httpbin.org/get?a=5&b=6',
    'https://httpbin.org/ip'
  )
))
```

Make request with any HTTP method

```{r}
(res <- cc$get())
```

You get back a list matching length of the number of input URLs

Access object variables and methods just as with `HttpClient` results, here just one at a time.

```{r}
res[[1]]$url
res[[1]]$success()
res[[1]]$parse("UTF-8")
```

Or apply access/method calls aross many results, e.g., parse all results

```{r}
lapply(res, function(z) z$parse("UTF-8"))
```

## varied request async

```{r}
req1 <- HttpRequest$new(
  url = "https://httpbin.org/get?a=5",
  opts = list(
    verbose = TRUE
  )
)
req1$get()

req2 <- HttpRequest$new(
  url = "https://httpbin.org/post?a=5&b=6"
)
req2$post(body = list(a = 5))

(res <- AsyncVaried$new(req1, req2))
```

Make requests asynchronously

```{r}
res$request()
```

Parse all results

```{r}
res$parse()
```

```{r}
lapply(res$parse(), jsonlite::prettify)
```

Status codes

```{r}
res$status_code()
```
