2016-12-05 1 views
3

내가 Node.js를 새로운 오전과 난 그냥 다른 함수 전에의 setTimeout 기능을 실행하는 방법을 모르는에서 작업을 실행하고 출력은 항상 세계 안녕하세요.Nodejs 예를 들어</p> <p>,</p> <pre><code>var async = require('async'); function hello(){ setTimeout(function(){ console.log('hello'); },2000);} function world(){ console.log("world"); } async.series([hello,world()]); </code></pre> <p>, 순서

라이브러리를 올바르게 사용하고 있습니까? 그 질문은 사소한 것 같지 않지만 긴 작업을 수행하기 위해 간단한 작업을 강제하는 방법을 모른다.

+0

몇 가지 문제 : 1) 식'세계는()'* 2)'hello' 반환 * 전 *'hello' 이제까지라고 함) 바로 (이 작업이 완료 world''실행 setTimeout이 완료되기 전에 *. 비동기를 사용하기 위해서는'callback'-idiom을 사용해야합니다. http://stackoverflow.com/questions/15969082/node-js-async-series-is-that-how-it-is-supposed-to-work- 이것은 world()의 문제점을 설명하고 사용법을 보여줍니다. 콜백 매개 변수 – user2864740

+0

그래서, 아니요 : 라이브러리를 잘못 사용하고 있습니다 (올바르게 동작을 설명하지 못함). 설명서를 읽고 예제를 검색하십시오. – user2864740

답변

3

Asynccallback를 사용해야합니다. this 링크를 따라 몇 가지 예를 봅니다. 다음 코드는해야 제대로 출력 hello world :

console.log('hello')을 대기하도록 callback()setTimeout() 함수 내에서 호출 된 것으로 도시
var async = require("async"); 
function hello(callback) { 
    setTimeout(function(){ 
     console.log('hello'); 
     callback(); 
    }, 2000); 
} 

function world(callback) { 
    console.log("world"); 
    callback(); 
} 

async.series([hello, world], function (err, results) { 
    // results is an array of the value returned from each function 
    // Handling errors here 
    if (err) { 
     console.log(err); 
    } 
}); 

.

-1

nodej의 핵심 인 콜백을 사용할 수 있습니다.

var fun1 = function(cb){ 
// long task 
// on done 
return cb(null, result); 
} 

var fun2 = function(cb){ 
return cb(null, data); 
} 

fun1(function(err, result){ 
if(!err){ 
    fun2(function(er, data){ 
    // do here last task 

    }) 
} 
} 

// to avoid pyramid of doom use native promises 

func1(){ 
return new Promise((resolve, reject) => { 
    // do stuff here 
    resolve(data) 
}) 

} 
func2(){ 
    return new Promise((resolve, reject) => { 
    resolve(data); 
    }) 
} 

그리고 사용하여 전화 :

func1.then((data) => { 
return func2(); 
}) 
.then((resule) => { 
//do here stuff when both promises are resolved 
}) 
+0

응답은'async' (주어진 콜백을 사용하는)의 문맥에 있어야합니다. 이것은 탑의 운명의 기초를 보여 주며 원래 코드의 문제를 설명하지 않습니다. – user2864740

+0

당신은 그 약속을 그냥 사용할 수 있습니다! 당신은 그것을하기 위해 비동기 lib를 요구하지 않거나 코드를 더 읽기 쉽게 만들기 위해 yield를 사용할 수도 있습니다. –

+0

감사합니다! 나는 nodejs에 익숙하지 않고 문법을 이해하지 못하기 때문에 콜백에 대해서도 더 공부할 것이다! –

-1

콜백 대신 약속을 사용할 수 있습니다. 코드는 다음과 같습니다.

var async = require('async'); 
    function hello(){ 
    setTimeout(function(){ 
     console.log('hello'); 
    },2000);} 

    function world(){ 
    console.log("world"); 
     } 
    return Q.fcall(function() { 
     hello(); 
    }) 
    .then(function(resultOfHelloFunction){ 
     world(); 
}); 

World() 함수는 hello() 함수가 실행 완료 될 때만 실행됩니다.

P.S : Q 라이브러리에서 을 약속합니다. 같은 것을 달성하기 위해 다른 라이브러리 (예 : bluebird)를 사용하는 것이 좋습니다.

+0

그가 '비동기'에 관해서 물어봤을 때 약속에 대한 대답을주는 것이별로 의미가 없다. – Paul

+0

감사합니다. 전에 약속을 결코 알지 못한다! –

0

사용 약속

function hello(){ 
    return new Promise(function(resolve, reject) { 
     console.log('hello'); 
     resolve(); 
    }); 
} 

function world(){ 
    return new Promise(function(resolve, reject) { 
     console.log("world"); 
     resolve(); 
    }); 
} 


    hello() 
    .then(function(){ 
    return world() 
    }) 
    .then(function(){ 
    console.log('both done'); 
    }) 
    .catch(function(err){ 
    console.log(err); 
    }); 
+0

감사합니다! 그것은 작동합니다! –

+0

당신이 upvote 제발 올바른 답변으로 표시 할 수 있습니다 당신을 위해 @ParosKwan –

관련 문제