[javascript] Bluebird를 사용하여 동기적인 코드 흐름에서 비동기 작업을 처리하는 방법을 알려주세요.
우선, Bluebird를 설치하고, Promise.promisify
메서드를 사용하여 콜백 기반의 비동기 함수를 프로미스로 변환합니다.
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
// 비동기로 파일 읽기
function readFileAsync(path) {
return fs.readFileAsync(path, 'utf8');
}
// 다음과 같이 사용할 수 있습니다
readFileAsync('example.txt')
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error(err);
});
위 예제에서는 fs.readFile
를 fs.readFileAsync
로 변환하여 프로미스 형태로 사용했습니다. 이제 readFileAsync
함수를 호출하면 프로미스를 반환하므로 .then
및 .catch
를 통해 결과 및 오류를 처리할 수 있습니다.
이와 같이 Bluebird를 사용하여 동기적인 코드 흐름으로 비동기 작업을 처리할 수 있습니다.