이 페이지의 내용
문서고급 기능
고급 기능03

실행 및 동기화

Promise와 async/await로 명령을 순차 또는 병렬 실행합니다.

한국어 문서약 7분

BindCommand 객체의 execute() 메소드는 Promise를 반환합니다. 이를 통해 async 및 await 키워드를 사용하여 비동기 작업을 동기적으로 처리할 수 있습니다.

ts
declare function execute(): Promise<void>;

• 명령(BindCommand)는 비동기적으로 작동합니다. • execute() 메소드는 서버 요청을 수행하며, 응답을 받을 때까지 기다릴 수 있습니다. • Promise의 특성을 활용하여 체인 호출(then) 또는 async/await 문법으로 동기적인 흐름을 구현할 수 있습니다.

명령 실행 및 동기화#

BindCommand 객체의 execute() 메소드는 Promise를 반환합니다. 이를 활용해 명령을 동기적으로 실행하거나 병렬로 실행할 수 있습니다.

ts
type OptionType = 'SEND' | 'VIEW' | 'ALL' | 'PICK'; // default 'SEND'
type SchemaType = 'AUTO' | 'DATA' | 'ENTITY';       // default 'AUTO'
type IndexType = number | number[]; // // default 0
type OutOptType = { option: OptionType, schema: SchemaType, index: IndexType }

declare function execute(
	outputOption?: OutOptType | OptionType | SchemaType | IndexType,
	config?: object | string
): Promise<void>;

declare const exec: typeof execute;
  • outputOption : 출력 옵션 설정
    • { option: 'VIEW', schema: 'DATA', index: 0} 와 같은 객체 형태로 지정하거나,
    • 'SEND', 'VIEW', 'ALL', 'PICK' 문자열로 option 을 지정할 수 있습니다.
  • config : axios 설정 객체 또는 요청 URL
    • 객체로 지정하면 axios의 설정 객체로 사용되며,
    • 문자열로 지정하면 요청할 URL 경로로 처리됩니다.
  • exec() 는 execute() 메소드의 별칭입니다.

Tip

execute() 실행 시 전달되는 outputOption과 config는 내부에 저장되지 않으며, 호출 시점에만 일회성으로 사용됩니다.

명령 실행시 옵션 지정#

execute() 실행시 outputOption 을 지정할 수 있습니다.

js
const bm = new BindModel();

bm.addCommand('cmd1');
bm.addCommand('cmd2');
bm.addCommand('cmd3');
bm.addCommand('cmd4');

bm.command['cmd1'].execute('VIEW');
bm.command['cmd2'].execute('DATA');
bm.command['cmd3'].execute({ option: 'PICK', schema: 'ENTITY' });
bm.command['cmd4'].execute({}, '/user');
  • cmd1 명령은 option = 'VIEW' 으로 실행합니다.
  • cmd2 명령은 schema = 'DATA' 으로 실행합니다.
  • cmd3 명령은 option = 'PICK', schema = 'ENTITY' 으로 실행합니다.
  • cmd4 명령은 url 이 '/user' 으로 실행합니다.

독립된 함수로 정의#

async await문을 사용하여 execute() 를 순차적으로 실행합니다.

CJS 환경

js
const bm = new BindModel();

bm.addCommand('cmd1');
bm.addCommand('cmd2');

async function executeCommands() {
    await bm.command['cmd1'].execute();
    console.log('Command 1 executed.');
    
    await bm.command['cmd2'].execute();
    console.log('Command 2 executed.');
}

// 호출
executeCommands();

ESM 환경

js
const bm = new BindModel();

bm.addCommand('cmd1');
bm.addCommand('cmd2');

await bm.command['cmd1'].execute();
console.log('Command 1 executed.');

await bm.command['cmd2'].execute();
console.log('Command 2 executed.');

사용자 함수를 fn 에 추가할 수 있습니다.

tip execute() 내부에 try 문으로 구성되어 있어서 오류발생시 cbError 콜백함수가 호출됩니다.

콜백함수를 이용한 동기화#

Promise의 then 메소드를 사용해 동기적인 실행 흐름을 구현할 수 있습니다.

js
const bm = new BindModel();

bm.addCommand('cmd1');
bm.addCommand('cmd2');

bm.command['cmd1'].execute()
    .then(() => {
        console.log('Command 1 executed.');
        return bm.command['cmd2'].execute();
    })
    .then(() => {
        console.log('Command 2 executed.');
    })
    .catch((err) => {
        console.error('Error executing commands:', err);
    });

사용자 정의 함수에 추가#

fn 컬렉션에 사용자 정의 동기화 함수를 추가하여 재사용성을 높일 수 있습니다.

js
const bm = new BindModel();

bm.addCommand('cmd1');
bm.addCommand('cmd2');

bm.fn.add('syncCommands', async function () {
    await bm.command['cmd1'].execute();
    await bm.command['cmd2'].execute();
});

// 호출
bm.fn.syncCommands();

비동기 명령 동시 실행#

Promise.all을 사용하여 여러 명령(BindCommand)을 동시에 실행할 수 있습니다.

js
const bm = new BindModel();

bm.addCommand('cmd1');
bm.addCommand('cmd2');
bm.addCommand('cmd3');

async function executeConcurrently() {
    await Promise.all([
        bm.command['cmd1'].execute(),
        bm.command['cmd2'].execute()
    ]);
    console.log('Command 1 and Command 2 executed concurrently.');

    await bm.command['cmd3'].execute();
    console.log('Command 3 executed.');
}

// 호출
executeConcurrently();
  • 'cmd1', 'cmd2' 을 동시에 실행이 완료되면 'cmd3'이 실행됩니다.

Tip Promise.all은 하나라도 실패하면 전체가 실패하므로, 에러 처리를 위해 try/catch를 사용하세요.

실행 에러 처리#

execute()는 내부적으로 try 문으로 보호되어 있어, 실패 시 cbError 콜백이 호출됩니다. 에러 처리는 catch 문에서 처리하거나 cbError 콜백을 활용합니다.

에러 처리는 기본 적으로 cbError 콜백 함수를 호출합니다.

js
bm.cbError = function (msg) {
    console.error('Global error handler:', msg);
};

catch 문에서 처리하여 에러를 처리합니다.

js
bm.command['cmd1'].execute()
    .catch((err) => {
        console.error('Error:', err);
    });

검색어를 입력해 보세요.