Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Promise

huliangjie edited this page Sep 3, 2020 · 1 revision

创建 Promise (from C#)

可在 C# 中直接创建 Promise, 代码生成器会自动识别参数中的 ScriptContext, 通过该值构造一个带返回值类型的 ScriptPromise 对象.

using UnityEngine;
using QuickJS;
using QuickJS.Native;
using QuickJS.Binding;

[JSType]
public class SampleBehaviour : MonoBehaviour
{
    private TypedScriptPromise<string> _p;

    public TypedScriptPromise<string> SimpleWait(ScriptContext ctx, int t)
    {
        if (_p != null)
        {
            return null;
        }

        _p = new TypedScriptPromise<string>(ctx);
        return _p;
    }

    // 想象一下, 这是个界面对话框, 这个 Promise 等待用户确定或者取消.
    void OnGUI()
    {
        var p = _p;
        if (p == null)
        {
            return;
        }
        
        if (GUILayout.Button("Resolve"))
        {
            _p = null;
            p.Resolve("执行成功测试, 我是一个C#字符串, 传给JS");
        }

        if (GUILayout.Button("Reject"))
        {
            _p = null;
            p.Reject("执行失败测试");
        }
    }
}
// 此例中 C# 定义的 SimpleWait 生成的签名是 SimpleWait(t: number): Promise<string>

async function test_custom_promise() {
    let go = new UnityEngine.GameObject("custome.promise.test");
    var sb = go.AddComponent(SampleBehaviour);
    let s = await sb.SimpleWait(1);
    print("after wait a promise (created in C#):", s);
}
test_custom_promise();
Clone this wiki locally