Skip to content
TheChatArchiveThe Chat Archive
DeepSeekdeepseek-r1-0528· DeepSeekHugging Face LMArena Human Preference 140K

With rust futures, how can I do something like a promise.all from nodejs ?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-pro’s answer.
  1. User

    With rust futures, how can I do something like a promise.all from nodejs ?

  2. DeepSeek Assistant

    To achieve functionality similar to JavaScript's Promise.all in Rust using futures, you can use the join_all function from the futures crate. This function concurrently executes a collection of futures and returns their results in a vector, preserving the original order.

    Step-by-Step Solution:

    1. Add Dependencies
      Include futures in your Cargo.toml:

      [dependencies]
      futures = "0.3"
      
    2. Using join_all
      Execute multiple futures concurrently and collect results:

      use futures::future::join_all;
      
      async fn fetch_data(url: &str) -> String {
          // Simulate async work (e.g., HTTP request)
          format!("Response from {}", url)
      }
      
      #[tokio::main]
      async fn main() {
          let urls = vec!["url1", "url2", "url3"];
          let futures = urls.into_iter().map(|url| fetch_data(url));
          
          // Run all futures concurrently, await their completion
          let results: Vec<String> = join_all(futures).await;
          
          println!("{:?}", results); 
          // Output: ["Response from url1", "Response from url2", "Response from url3"]
      }
      

    Key Points:

    • Concurrency: join_all runs futures concurrently (not in parallel by default; depends on the executor).
    • Order: Results are returned in the same order as the input futures.
    • Error Handling: If any future fails (returns Err), join_all will still resolve successfully but include the Err in the result vector. To fail immediately on any error (like Promise.all), use try_join_all:
      use futures::future::try_join_all;
      
      async fn main() -> Result<(), MyError> {
          let results: Vec<String> = try_join_all(futures).await?;
          Ok(())
      }
      

    For Heterogeneous Futures:

    If your futures have different return types, box them into a common trait object:

    use futures::future::{BoxFuture, FutureExt};
    
    async fn main() {
        let future1 = async { 42 }.boxed();          // BoxFuture<'static, i32>
        let future2 = async { "hello".to_string() }.boxed(); // BoxFuture<'static, String>
        
        let futures: Vec<BoxFuture<'static, _>> = vec![future1, future2];
        let results = join_all(futures).await;
        
        println!("{:?}", results); // [42, "hello"]
    }
    

    Notes:

    • Use .boxed() to convert futures into type-erased BoxFuture (requires FutureExt trait).
    • join_all is ideal for dynamic collections of futures. For fixed-size sets, consider futures::join! (statically known size).

    This approach efficiently handles concurrent async operations, similar to Promise.all in Node.js.

  3. User

    I'm getting this error when I try to Box each future:

    error[E0308]: mismatched types
      --> src/main.rs:27:9
       |
    27 |         asd.boxed()
       |         ^^^^^^^^^^^ expected `User`, found `Pin<Box<...>>`
       |
       = note: expected struct `Pin<Box<dyn futures::Future<Output = Result<User, error_stack::report::Report<ApiClientError>>> + std::marker::Send>>`
                  found struct `Pin<Box<dyn futures::Future<Output = Result<Pin<Box<dyn futures::Stream<Item = String> + std::marker::Send>>, FirestoreError>> + std::marker::Send>>`
    
    
  4. DeepSeek Assistant

    The error occurs because you're trying to box futures with different output types into the same collection. Rust requires all elements in a Vec to have the same type. Here's how to fix it:

    Solution: Use an Enum to Unify Different Result Types

    1. Create an enum that can hold all possible result types
    2. Map each future to return this common enum type
    3. Use join_all on the unified futures
    use futures::{future::join_all, FutureExt, Stream, StreamExt};
    use std::pin::Pin;
    
    // Define your custom types
    struct User;
    enum ApiClientError {}
    enum FirestoreError {}
    
    // Create a unified result enum
    enum AsyncResult {
        UserResult(Result<User, error_stack::report::Report<ApiClientError>>),
        StreamResult(Result<Pin<Box<dyn Stream<Item = String> + Send>>, FirestoreError>),
    }
    
    #[tokio::main]
    async fn main() {
        // Create futures mapped to the common type
        let future1 = fetch_user()
            .map(|res| AsyncResult::UserResult(res))
            .boxed();
    
        let future2 = fetch_stream()
            .map(|res| AsyncResult::StreamResult(res))
            .boxed();
    
        // Run concurrently
        let results = join_all(vec![future1, future2]).await;
    
        // Process results
        for res in results {
            match res {
                AsyncResult::UserResult(user_res) => {
                    // Handle user result
                }
                AsyncResult::StreamResult(stream_res) => {
                    // Handle stream result
                }
            }
        }
    }
    
    // Example async functions
    async fn fetch_user() -> Result<User, error_stack::report::Report<ApiClientError>> {
        // ... implementation
        Ok(User)
    }
    
    async fn fetch_stream() -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, FirestoreError> {
        // ... implementation
        let stream = futures::stream::iter(vec!["data".to_string()]);
        Ok(stream.boxed())
    }
    

    Key Points:

    1. Enum Unification:

      • The AsyncResult enum wraps different possible result types
      • Each future is mapped to return this common enum type
    2. Type Erasure:

      • boxed() converts futures to BoxFuture trait objects
      • All futures in the Vec now have the same type: BoxFuture<'static, AsyncResult>
    3. Result Handling:

      • Use pattern matching to handle different result types after execution
      • Maintain type safety while supporting heterogeneous outputs

    Alternative for Fixed Number of Futures:

    If you have a fixed number of futures with different types, use join! instead:

    use futures::join;
    
    async fn main() {
        let (user_res, stream_res) = join!(fetch_user(), fetch_stream());
        
        // Directly access results without boxing
        match user_res {
            Ok(user) => /* handle user */,
            Err(e) => /* handle error */,
        }
        
        match stream_res {
            Ok(stream) => /* handle stream */,
            Err(e) => /* handle error */,
        }
    }
    

    This approach is more efficient but only works when the number and types of futures are known at compile time. For dynamic collections, the enum-based solution is required.

  5. User

    Nvm! This is the errors I'm getting:

    error[E0308]: mismatched types
      --> src/main.rs:27:9
       |
    27 |         asd.boxed()
       |         ^^^^^^^^^^^ expected `User`, found `Pin<Box<...>>`
       |
       = note: expected struct `Pin<Box<dyn futures::Future<Output = Result<User, error_stack::report::Report<ApiClientError>>> + std::marker::Send>>`
                  found struct `Pin<Box<dyn futures::Future<Output = Result<Pin<Box<dyn futures::Stream<Item = String> + std::marker::Send>>, FirestoreError>> + std::marker::Send>>`
    
    
    
  6. DeepSeek Assistant

    The error occurs because you're trying to box futures with different output types into a collection, but Rust requires all elements in a vector to have the same type. Let me break down the problem and provide a solution:

    Understanding the Error

    The compiler is telling you:

    1. It expected a future resolving to Result<User, ...>
    2. It found a future resolving to Result<Pin<Box<dyn Stream<...>>, ...>

    These are fundamentally different types that can't be stored together in a collection.

    Solution: Unify Types with an Enum

    You need to create a common type that can represent both results:

    use futures::{Stream, StreamExt, FutureExt};
    use std::pin::Pin;
    
    // Define a unified result type
    enum AsyncResult {
        User(Result<User, error_stack::report::Report<ApiClientError>>),
        Stream(Result<Pin<Box<dyn Stream<Item = String> + Send>>, FirestoreError>),
    }
    
    // Your existing async functions
    async fn fetch_user() -> Result<User, ...> { /* ... */ }
    async fn fetch_stream() -> Result<Pin<Box<dyn Stream<Item = String> + Send>>, FirestoreError> { /* ... */ }
    
    // Usage
    let future1 = fetch_user()
        .map(AsyncResult::User)
        .boxed();
    
    let future2 = fetch_stream()
        .map(AsyncResult::Stream)
        .boxed();
    
    let futures = vec![future1, future2];
    let results = join_all(futures).await;
    

    Handling Results

    Process the results using pattern matching:

    for res in results {
        match res {
            AsyncResult::User(user_result) => {
                match user_result {
                    Ok(user) => /* handle user */,
                    Err(e) => /* handle error */,
                }
            }
            AsyncResult::Stream(stream_result) => {
                match stream_result {
                    Ok(stream) => {
                        let items: Vec<_> = stream.collect().await;
                        /* handle items */
                    }
                    Err(e) => /* handle error */,
                }
            }
        }
    }
    

    Alternative Approach: Separate Collections

    If you don't need to mix the futures in the same collection, keep them separate:

    let user_futures = vec![fetch_user().boxed()];
    let stream_futures = vec![fetch_stream().boxed()];
    
    let user_results = join_all(user_futures).await;
    let stream_results = join_all(stream_futures).await;
    

    Key Points:

    1. Type Unification: The enum creates a common type for different async results
    2. Boxing Correctly: Each future is mapped to the enum variant before boxing
    3. Result Handling: Pattern matching ensures type-safe handling of different outcomes
    4. Stream Processing: Use .collect().await to consume streams if needed

    This approach maintains type safety while allowing you to manage different async operations together, similar to Promise.all in JavaScript.

  7. User

    So every time I want to join futures, I have to construct an enum ? This seems a bit bothersome, is there an easier way ?

  8. DeepSeek Assistant

    You've hit on a key pain point in Rust's async system! 😅 While the enum approach is type-safe and explicit, it can feel heavy-handed. Let me show you some alternatives and workarounds:

    1. For Fixed-Size Sets: Use join! (No Enum Needed!)

    If you know the number and types of futures at compile time, use futures::join!:

    use futures::join;
    
    async fn main() {
        let future1 = fetch_user();
        let future2 = fetch_stream();
        
        match join!(future1, future2) {
            (Ok(user), Ok(stream)) => {
                // Handle both successes
            }
            (Err(e), _) => /* handle user error */,
            (_, Err(e)) => /* handle stream error */,
        }
    }
    

    2. Trait Objects (Lose Type Safety)

    If you don't care about individual results and just want to wait for completion:

    let futures: Vec<BoxFuture<()>> = vec![
        fetch_user().map(|_| ()).boxed(),
        fetch_stream().map(|_| ()).boxed(),
    ];
    
    join_all(futures).await;
    

    3. Type Erasure with Box<dyn Any>

    For heterogeneous futures where you need results but don't want enums:

    use std::any::Any;
    
    let futures = vec![
        fetch_user()
            .map(|res| Box::new(res) as Box<dyn Any + Send>)
            .boxed(),
        fetch_stream()
            .map(|res| Box::new(res) as Box<dyn Any + Send>)
            .boxed(),
    ];
    
    for result in join_all(futures).await {
        if let Some(user_res) = result.downcast_ref::<Result<User, _>>() {
            // Handle user result
        } else if let Some(stream_res) = result.downcast_ref::<Result<Pin<Box<dyn Stream<...>>, _>>() {
            // Handle stream result
        }
    }
    

    4. Macro for Enum Generation (Advanced)

    Create a macro to generate enums automatically:

    macro_rules! async_results {
        ($($name:ident($ty:ty)),* $(,)?) => {
            enum AsyncResult {
                $($name($ty)),*
            }
            
            $(
                impl From<$ty> for AsyncResult {
                    fn from(val: $ty) -> Self {
                        AsyncResult::$name(val)
                    }
                }
            )*
        };
    }
    
    // Declare your result types
    async_results! {
        UserResult(Result<User, ...>),
        StreamResult(Result<Pin<Box<dyn Stream<...>>, ...>)
    }
    

    5. Separate Execution (Simplest for Many Cases)

    Run different future types separately:

    #[tokio::main]
    async fn main() {
        let user_task = tokio::spawn(fetch_user());
        let stream_task = tokio::spawn(fetch_stream());
        
        let user_result = user_task.await.unwrap();
        let stream_result = stream_task.await.unwrap();
    }
    

    Why Rust Requires This

    The fundamental reason is Rust's strict static typing:

    • JavaScript's Promise.all works because JS is dynamically typed
    • Rust needs to know memory layout and types at compile time
    • Async functions return different concrete Future types

    Recommendation

    For most cases:

    1. Use join! for 2-5 futures of different types
    2. Use separate tokio::spawn for independent operations
    3. Use join_all only for homogeneous futures
    4. Only use the enum approach when you need a collection of mixed futures

    The friction is real, but it's the price for Rust's memory safety and zero-cost abstractions. The async ecosystem is still evolving, and future improvements might make this easier!

  9. User

    I have this rust code:

    (collections as BoxStream<String>).for_each_concurrent(None, |collection| {
                    println!("Doco {}", collection);    
                });
    

    But I'm getting this error:

    error[E0277]: `()` is not a future
        --> src/main.rs:37:48
         |
    37   |             (collections as BoxStream<String>).for_each_concurrent(None, |collection| {
         |                                                ^^^^^^^^^^^^^^^^^^^ `()` is not a future
         |
         = help: the trait `futures::Future` is not implemented for `()`
    note: required by a bound in `for_each_concurrent`
        --> /Users/mindera/.cargo/registry/src/index.crates.io-6f17d22bba15001f/futures-util-0.3.31/src/stream/stream/mod.rs:1154:14
         |
    1147 |     fn for_each_concurrent<Fut, F>(
         |        ------------------- required by a bound in this associated function
    ...
    1154 |         Fut: Future<Output = ()>,
         |              ^^^^^^^^^^^^^^^^^^^ required by this bound in `StreamExt::for_each_concurrent`
    
    
    
  10. DeepSeek Assistant

    The error occurs because for_each_concurrent expects the closure to return a future, but your closure returns () (unit type) instead. Here's how to fix it:

    Solution 1: Wrap in an async block (recommended)

    use futures::StreamExt;
    
    (collections as BoxStream<String>)
        .for_each_concurrent(None, |collection| async move {
            println!("Doco {}", collection);
        })
        .await;
    

    Solution 2: Use futures::future::ready

    use futures::{future, StreamExt};
    
    (collections as BoxStream<String>)
        .for_each_concurrent(None, |collection| {
            println!("Doco {}", collection);
            future::ready(())
        })
        .await;
    

    Key points:

    1. The closure must return a future that resolves to ()
    2. Async blocks implicitly create futures
    3. future::ready(()) creates an immediately-ready future
    4. .await is required to execute the stream processing

    Why this happens:

    • for_each_concurrent is designed to handle asynchronous operations per item
    • Your closure only does a synchronous println!
    • Rust needs to know this should be treated as an async operation

    Full corrected example:

    use futures::{stream, StreamExt, Stream};
    use std::pin::Pin;
    
    type BoxStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
    
    #[tokio::main]
    async fn main() {
        let collections: BoxStream<String> = Box::pin(stream::iter(vec![
            "coll1".to_string(),
            "coll2".to_string(),
        ]));
    
        collections
            .for_each_concurrent(None, |collection| async move {
                println!("Doco {}", collection);
                // Add async work here if needed:
                // tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            })
            .await;
    }
    

    If you need actual async work:

    collections
        .for_each_concurrent(None, |collection| async move {
            println!("Starting {}", collection);
            
            // Simulate async work
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            
            println!("Finished {}", collection);
        })
        .await;
    

    This pattern allows concurrent processing of stream items while maintaining proper async behavior. The async move block creates the required future, and .await drives the execution.

  11. User

    How do I print the current time in milliseconds ?

  12. DeepSeek Assistant

    To print the current time in milliseconds in Rust, you have several options depending on your needs:

    1. Using the Standard Library (no dependencies)

    use std::time::{SystemTime, UNIX_EPOCH};
    
    fn main() {
        let now = SystemTime::now();
        let since_epoch = now.duration_since(UNIX_EPOCH).expect("Time went backwards");
        
        // Total milliseconds since epoch
        let ms = since_epoch.as_millis();
        println!("Current time (ms): {}", ms);
        
        // With fractional milliseconds
        let ms_fractional = since_epoch.as_secs_f64() * 1000.0;
        println!("Current time (ms with fractions): {:.3}", ms_fractional);
    }
    

    2. Using the chrono Crate (more features)

    Add to Cargo.toml:

    [dependencies]
    chrono = "0.4"
    

    Code:

    use chrono::Utc;
    
    fn main() {
        // Milliseconds since Unix epoch
        let ms = Utc::now().timestamp_millis();
        println!("Current time (ms): {}", ms);
        
        // With formatting (local time)
        let now = chrono::Local::now();
        println!(
            "Formatted: {}.{:03}", 
            now.format("%H:%M:%S"), 
            now.timestamp_subsec_millis()
        );
    }
    

    3. Using the time Crate (modern alternative)

    Add to Cargo.toml:

    [dependencies]
    time = "0.3"
    

    Code:

    use time::OffsetDateTime;
    
    fn main() {
        // Milliseconds since Unix epoch
        let ms = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
        println!("Current time (ms): {}", ms);
        
        // With formatting
        let now = OffsetDateTime::now_local().unwrap();
        println!(
            "Formatted: {}.{:03}",
            now.format("%H:%M:%S"),
            now.millisecond()
        );
    }
    

    Key differences:

    MethodProsCons
    std::timeNo dependencies, always availableBasic functionality only
    chronoRich formatting, timezone supportLarger dependency
    time (0.3+)Modern API, standard-compliantSlightly less mature

    For precise timing (e.g., benchmarks):

    use std::time::Instant;
    
    fn main() {
        let start = Instant::now();
        // ... your code ...
        let elapsed_ms = start.elapsed().as_millis();
        println!("Elapsed: {} ms", elapsed_ms);
    }
    

    Choose the method based on your needs:

    • For simple timestamp: std::time or chrono::Utc::now().timestamp_millis()
    • For formatted output: chrono or time crates
    • For precise duration measurements: std::time::Instant

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.