Skip to content

[question] Why do I need to be an arrow function when calling a javascript function asynchronously? #10956

@nabezokodaikon

Description

@nabezokodaikon

Why do I need to be an arrow function when calling a javascript function asynchronously?
If you define it in function normally, you will get an error that it is not defined.

Cargo.toml

[lib]
crate-type = ["cdylib"]

[dependencies]
js-sys = "0.3.51"
wasm-bindgen = "0.2.74"
wasm-bindgen-futures = "0.4.24"

[dependencies.web-sys]
version = "0.3.51"
features = [
  'console'
]

lib.rs

use js_sys::Promise;
use std::f64;
use wasm_bindgen::prelude::*;
use wasm_bindgen_futures::JsFuture;
use web_sys::console::log_1;

#[wasm_bindgen]
extern "C" {
    fn sleep(ms: f64) -> Promise;
}

#[wasm_bindgen]
pub fn console_log(s: &str) {
    #[allow(unused_unsafe)]
    unsafe {
        log_1(&JsValue::from(String::from(s)));
    }
}

#[wasm_bindgen]
pub async fn timer(count: u32) -> Result<JsValue, JsValue> {
    for i in 1..count {
        unsafe {
            JsFuture::from(sleep(1000f64)).await?;
        }
        console_log(&i.to_string());
    }

    Ok(JsValue::undefined())
}

timer.ts

import init, {
  timer,
} from "../pkg/wasm_timer.js";

// It works.
// const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

// An error will occur.
function sleep(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

async function run() {
  const wasm = await fetch("public/pkg/wasm_timer_bg.wasm");
  await init(wasm);
  timer(10);
}

run();

build.sh

#!/bin/bash
cargo build --target wasm32-unknown-unknown --release
wasm-bindgen target/wasm32-unknown-unknown/release/wasm_timer.wasm --target web --out-dir ./public/pkg
deno bundle public/ts/timer.ts public/js/timer.js

スクリーンショット 2021-06-14 22 31 30

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions