2016-11-01 2 views
1

텍스트 파일을 읽고, 모든 것을 문자열에 넣고, 모든 줄마다 문자열을 나눠서 배열에 넣고 임의로 하나씩 반환하는 비동기 함수를 노드에 가지고 있습니다. 여기에 내가 그것을 다루는 새로운 약속의 기능을 구현 한 :node.js의 비동기 함수에서 Promise를 올바르게 사용하려면 어떻게해야합니까?

여기
exports.readTextFileAndReturnRandomLine = function readTextFile(file) 
{ 
    //reads text file as string, splits on new line and inserts into array, returns random array element 
    return new Promise((resolve, reject) => 
    { 
     var fs = require('fs'); 
     var textFile = fs.readFile(file, 'utf8', (err, data) => 
     { 
      if (err) 
      { 
       return reject(err); 
      } 
      else 
      { 
       var array = data.toString().split("\n"); 
       var response = array[Math.floor(Math.random() * array.length)]; 
       return resolve(response); 
      } 
     }); 
    }); 
} 

는 함수에서 읽고 텍스트 파일입니다 내 루트 노드 (app.js)에서 이제

Hello there, 
Howdy, 
I will remember your name, 
Thanks for telling me, 
Hi 
Noted, 
Thanks 
Well hello there 
Nice to meet you 
The pleasure is all mine, 
Nice name, 

, 나는 기능과 같이 호출합니다.

intents.matches('RememberName', [ 
    function (session, args, next) { 
     var nameEntity = builder.EntityRecognizer.findEntity(args.entities, 'name'); 
     if (!nameEntity) 
     { 
      builder.Prompts.text(session, "Sorry, didn't catch your name. What is it?"); 
     } else 
     { 
      next({ response: nameEntity.entity }); 
     } 
    }, 
    function (session, results) { 
     if (results.response) 
     {   
      fileReader.readTextFileAndReturnRandomLine('./text/remembername.txt').then(function(value) { 
       console.log(value + ", " + results.response); 
      }).catch(function(reason) { 
       console.log(reason); 
      }); 
     } 
     else 
     { 
      session.send("Ok"); 
     } 
    } 
]); 

문제는 valuename 변수가 나는에 넣어 한 순서대로 콘솔에 인쇄되지 않는 것입니다 여기에 내 실제 출력 : 여기

my name is chris 
, Chrisfor telling me, 
my name is Chris 
, Chris 
my name is Chris 
, Chris 
my name is Chris 
, Chrishere, 
my name is Chris 
, Chrisfor telling me, 
my name is Chris 
, Chrisasure is all mine, 
my name is Chris 
, Chris 
my name is Chris 
, Chris 
my name is Chris 
, Chrisllo there 

그리고 내 예상 출력 :

my name is Chris 
Hello there, Chris 
my name is Chris 
Howdy, Chris 
my name is Chris 
Nice to meet you Chris 
my name is Chris 
Nice name, Chris 

나는 그것이 모든 것의 동시성 함께 할 수있는 뭔가가하지만 난 아니 수 있다고 생각 나의 삶은 그것이 무엇인지 알아 낸다.

+0

"return"없이 답장을 시도 할 수 있습니까? resolve (response); 반환 거절 (err); – donlys

+0

@donlys이 시도하고 불행히도 동일한 결과를 생성합니다 : ( – blueprintChris

+0

다음 절을 사용하여 다음 절을 시도 할 수 있습니다 (function (value) {console.log (value + ","+ name);}) catch (이유) {console.log (이유)}) – donlys

답변

1

텍스트 파일에서 문자열로 가져온 '\r' 문자가 반환되었습니다. response.trim() 메서드를 적용하면 문제가 해결됩니다.

0

오케이. 따라서 코드에 약간의 오류가 있습니다. 약속의 정의는 resolvereject의 두 가지 기능을 필요로합니다.

하지만 약속 할 때 then()catch()을 사용하십시오. resolve()then()이고 reject()catch()입니다.

var name = "Chris"; 
fileReader.readTextFileAndReturnRandomLine('./text/remembername.txt').then(function(value){    
    console.log(value + ", " + name); 

}).catch(function(reason) { 
    console.log(reason); 
}); 

내가이 일을 생각 :

그래서 당신이해야 할 모든이에 코드의 마지막을 약간 수정 한 것입니다.

+0

불행하게도 이것은 작동하지 않습니다. 출력은 여전히 ​​동일합니다 - 내 이름이 먼저 인쇄되고 Promise의 값이 상단/옆에 인쇄됩니다. – blueprintChris

+0

@blueprintChris 내 결과물은 다음과 같습니다. ⑫ 데스크톱 노드 텍스트 .js 나는 당신의 이름을 기억할 것입니다., Chris Desk 상위 노드 text.js 안녕하세요, 크리스 ➜ 데스크톱 노드 text.js 안녕하세요, 만나서 크리스 ➜ 데스크톱 노드 text.js 니스, 크리스 ➜ 데스크톱 노드 텍스트입니다.js 나는 당신의 이름을 기억할 것입니다., Chris 데스크탑 노드 text.js 감사합니다, Chris ➜ 바탕 화면 ' –

+0

여기에 붙여 넣은 파일과 여기에 올린 코드는 내가 바꾼 것에서 작동합니다. 코드 또는 파일을 확인하십시오. –

관련 문제