์ด๋ค ๋ฒ์ ์ ๋น๋๊ธฐ๋ฅผ ์ฌ์ฉํ๊ณ ์์ต๋๊น?
2.5.0
(๋
ธ๋ ๋ฒ์ / ๋ธ๋ผ์ฐ์ ๋ฒ์ )์์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ ํ๊ฒฝ
๋
ธ๋ 8
๋ญ ํ์ด?
async=require('async')
async function myFirstFunction(callback) {
callback(null, 'one', 'two');
}
function mySecondFunction(arg1, arg2, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
callback(null, 'three');
}
async function myLastFunction(arg1, callback) {
// arg1 now equals 'three'
callback(null, 'done');
}
async.waterfall([
myFirstFunction,
mySecondFunction,
myLastFunction,
], function (err, result) {
// result now equals 'done'
console.log(err, result)
});
๋ฌด์จ ์ผ์ด ์ผ์ด๋๊ธฐ๋ฅผ ๊ธฐ๋ ํ์ต๋๊น?
์์ธ๊ฐ ์๋ค
์ค์ ๊ฒฐ๊ณผ๋ ๋ฌด์์ ๋๊น?
> TypeError: callback is not a function
at myFirstFunction (repl:2:5)
at /Users/scott/node_modules/async/dist/async.js:143:27
at /Users/scott/node_modules/async/dist/async.js:21:12
at nextTask (/Users/scott/node_modules/async/dist/async.js:5297:14)
at Object.waterfall (/Users/scott/node_modules/async/dist/async.js:5307:5)
at repl:1:7
at ContextifyScript.Script.runInThisContext (vm.js:44:33)
at REPLServer.defaultEval (repl.js:239:29)
at bound (domain.js:301:14)
at REPLServer.runBound [as eval] (domain.js:314:12) undefined
์ฝ๋ฐฑ์ async
ํจ์์ ์ ๋ฌ๋์ง ์๊ณ ๋์ ๊ฐ์ ๋ฐํํฉ๋๋ค.
myFirstFunction
callback
์ ๋ ์ด์์ ์ธ์๊ฐ ์ ๋ฌ๋๋ ์์ ์ฒซ ๋ฒ์งธ ํจ์์ ๊ฒฝ์ฐ ๋์ ๋ฐฐ์ด์ ๋ฐํํด์ผํฉ๋๊น?
์, ๋ค์๊ณผ ๊ฐ์ด ํ ์ ์์ต๋๋ค.
async.waterfall([
// ...
async function (arg1, arg2) {
//...
const arg3 = await foo()
return [arg1, arg2, arg3]
},
function ([arg1, arg2, arg3], callback) {
//...
}
๊ทธ๋ ๋ค๋ฉด ์ค๋ฅ๋ฅผ ๋ฐํํ๋ ๋ฐฉ๋ฒ์ ๋ฌด์์ ๋๊น? ๊ทธ๋ฅ ๋์ ธ?
์์ ์ง๋ฌธ์ ๋ํ ๋ต์ด ์์ต๋๊น? ๋๋ ๋น๋๊ธฐ ํจ์์์ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ ๋ ๋ณด์๊ธ์ ๋ด๊ฒ ๋ค๊ณ ๋ฏฟ์ต๋๋ค. ์ฌ์ ํ "next"์ฝ๋ฐฑ์ ํธ์ถํด์ผํฉ๋๋ค.
์ด๊ฑด ์ด๋์?
async.waterfall([
// ...
async function (arg1, arg2, callback) {
//...
try {
const arg3 = await foo()
return [arg1, arg2, arg3]
} catch (err) {
callback('An error occured:' + err.message);
}
},
function ([arg1, arg2, arg3], callback) {
//...
}
async
ํจ์๋ ์ ๋ฌ ๋ ์ฝ๋ฐฑ์๋ฐ์ง ์์ต๋๋ค. throw
์ค๋ฅ์
๋๋ค.
๊ฐ์ฌ.
๊ฐ์ฅ ์ ์ฉํ ๋๊ธ
์, ๋ค์๊ณผ ๊ฐ์ด ํ ์ ์์ต๋๋ค.