---
title: 'Await Promise'
description: Aguarde uma Promise JavaScript no Rust.
---

# Await Promise

Aguardar uma `Promise` JavaScript em Rust parece loucura, mas é viável em **NAPI-RS**.

::: tip
Aguardar uma `Promise` JavaScript requer a feature `async` ou `tokio_rt`;
`tokio_rt` habilita `napi4` automaticamente.

:::

::: info
`Promise<T>` é `Send` quando `T` é `Send`; assim, o compilador impede que um
valor resolvido não-`Send` atravesse threads worker do Tokio.

:::

**lib.rs**

```rust
use napi::bindgen_prelude::*;
use napi_derive::napi;

#[napi]
pub async fn async_plus_100(p: Promise<u32>) -> Result<u32> {
  let v = p.await?;
  v.checked_add(100)
    .ok_or_else(|| Error::new(Status::InvalidArg, "result exceeds u32"))
}
```

**test.mjs**

```js {4}
import { asyncPlus100 } from './index.js'

const fx = 20
const result = await asyncPlus100(
  new Promise((resolve) => {
    setTimeout(() => resolve(fx), 50)
  }),
)

console.log(result) // 120
```
