# async/await

Each script supports asynchronous wait by async / await.

## Asynchronous wait method

The implemented asynchronous wait method is as follows.

- PlayableBehaviour.Yield
  Wait until the next OnUpdate call.
- ActionBehaviour.WaitForExecute
  Wait until the next OnExecute call.
  After waiting, it will be treated the same as in OnExecute, so you can call FinishExecute.

### Yield usage example

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    using UnityEngine;
    using Arbor;

    [AddComponentMenu("")]
    public class ExampleAwaitBehaviour : StateBehaviour
    {
    	public StateLink nextState;

    	async void WaitFrame(int frameCount)
    	{
    		try
    		{
    			int startFrame = Time.frameCount;

    			for (int i = 0; i < frameCount; i++)
    			{
    				await Yield();
    			}

    			Debug.Log($"{Time.frameCount - startFrame}");

    			Transition(nextState);
    		}
    		catch (System.Exception ex)
    		{
    			if (ex is System.OperationCanceledException)
    			{
    				return;
    			}

    			Debug.LogException(ex);
    		}
    	}

    	public override void OnStateBegin()
    	{
    		WaitFrame(10);
    	}
    }

When this script is executed, `await Yield();` is executed 10 times, and then `9` is output to Console for transition.
Note that in this example, the OnStateBegin call and the first `await Yield ();` call will be in the same frame.

## CancellationTokenOnEnd

PlayableBehaviour.CancellationTokenOnEnd

A token that cancels asynchronous waits when exiting a node or destroying an instance.
The Yield and WaitForExecute methods are now canceled with this token.
Use this cancel token if necessary if you want other methods to perform asynchronous wait processing.

If canceled, a `System.OperationCanceledException` will be thrown.
The caller should catch the exception and cancel it appropriately.

## UniTask

If you have UniTask installed, you can convert it to UniTask type with `Yeild().ToUniTask()`.

See Use of UniTask to enable the ToUniTask method.