bluebird
콜백 API를 약속으로 변환 중.
수색…
비고
약속에는 상태가 있으며, 보류 상태로 시작하여 정착 할 수 있습니다.
- 계산이 성공적으로 완료 되었음을 의미합니다.
- rejected 는 계산이 실패했음을 의미합니다.
약속 한 반환 함수 는 절대로 throw해서는 안되며 , 대신 거부를 반환해야합니다. 약속 반환 함수를 .catch } catch { 와 } catch { 모두 사용해야합니다. 약속 된 API를 사용하는 사람들은 약속 할 것을 기대하지 않습니다. JS에서 비동기 API가 작동하는 방식을 잘 모르는 경우 먼저이 답변을 참조하십시오 .
한 번에 전체 NodeJS 모듈 변환
콜백을 반환하는 라이브러리가 있다고 가정 해 봅시다 (예 : NodeJS의 fs 모듈).
const fs = require("fs");
fs.readFile("/foo.txt", (err, data) => {
if(err) throw err;
console.log(data);
});
우리는 API를 promisifyAll 와 함께 반환하는 약속으로 변환하려고합니다. 우리는 promisifyAll 을 사용하여 전체 API를 약속을 사용하도록 변환합니다.
const Promise = require("bluebird");
const fs = Promise.promisifyAll(require("fs"));
// this automatically adds `Async` postfixed methods to `fs`.
fs.readFileAsync("/foo.txt").then(console.log);
따라서 전체 모듈을 약속으로 사용할 수 있습니다.
다음은 특정 모듈을 약속하는 방법에 대한 일반적인 예제입니다.
// The most popular redis module
var Promise = require("bluebird");
Promise.promisifyAll(require("redis"));
// The most popular mongodb module
var Promise = require("bluebird");
Promise.promisifyAll(require("mongodb"));
// The most popular mysql module
var Promise = require("bluebird");
// Note that the library's classes are not properties of the main export
// so we require and promisifyAll them manually
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);
// Mongoose
var Promise = require("bluebird");
Promise.promisifyAll(require("mongoose"));
// Request
var Promise = require("bluebird");
Promise.promisifyAll(require("request"));
// Use request.getAsync(...) not request(..), it will not return a promise
// mkdir
var Promise = require("bluebird");
Promise.promisifyAll(require("mkdirp"));
// Use mkdirp.mkdirpAsync not mkdirp(..), it will not return a promise
// winston
var Promise = require("bluebird");
Promise.promisifyAll(require("winston"));
// rimraf
var Promise = require("bluebird");
// The module isn't promisified but the function returned is
var rimrafAsync = Promise.promisify(require("rimraf"));
// xml2js
var Promise = require("bluebird");
Promise.promisifyAll(require("xml2js"));
// jsdom
var Promise = require("bluebird");
Promise.promisifyAll(require("jsdom"));
// fs-extra
var Promise = require("bluebird");
Promise.promisifyAll(require("fs-extra"));
// prompt
var Promise = require("bluebird");
Promise.promisifyAll(require("prompt"));
// Nodemailer
var Promise = require("bluebird");
Promise.promisifyAll(require("nodemailer"));
// ncp
var Promise = require("bluebird");
Promise.promisifyAll(require("ncp"));
// pg
var Promise = require("bluebird");
Promise.promisifyAll(require("pg"));
단일 NodeJS 함수 변환
당신은에 콜백 인수로 하나의 기능을 변환 할 수 있습니다 Promise 과 -returning 버전 Promise.promisify , 그래서이 :
const fs = require("fs");
fs.readFile("foo.txt", (err, data) => {
if(err) throw err;
console.log(data);
});
다음과 같이됩니다.
const promisify = require("bluebird");
const readFile = promisify(require("fs").readFile));
readFile("foo.txt").then(console.log); // promisified version
다른 콜백 API 변환
promisify 및 promisifyAll 버전이 맞지 않는다고 가정하면 콜백 API를 약속으로 변환하기 위해 promise 생성자를 사용할 수 있습니다.
약속 생성은 일반적으로 정산 시점을 지정하는 것을 의미합니다. 즉, 이행 된 (완료 됨) 또는 거부 된 (오류가 발생한) 단계로 이동하여 데이터를 사용할 수 있음을 나타내며 ( .then 로 액세스 할 수 있음) 것을 의미합니다.
new Promise((fulfill, reject) => { // call fulfill/reject to mark the promise
someCallbackFunction((data) => {
fulfill(data); // we mark it as completed with the value
})
});
예를 들어 약속을 사용하도록 setTimeout 을 변환 해 봅시다.
function delay(ms) { // our delay function that resolves after ms milliseconds
return new Promise((resolve, reject) => { // return a new promise
setTimeout(resolve, ms); // resolve it after `ms` milliseconds have passed
})
}
// or more concisely:
const delay = ms => new Promise(r => setTimeout(r, ms));
이제 함수를 반환하는 일반적인 약속처럼 사용할 수 있습니다.
delay(1000).then(() => console.log("One second passed")).
then(() => delay(1000)).
then(() => console.log("Another second passed"));