[javascript] 약속, 추가 매개 변수를 전달한 다음 연결

예를 들어 약속 :

var P = new Promise(function (resolve, reject) {
  var a = 5;
  if (a) {
    setTimeout(function(){
      resolve(a);
    }, 3000);
  } else {
    reject(a);
  }
});

우리가 호출 한 후 프라 미스에 대한 메소드 :

P.then(doWork('text'));

doWork 함수는 다음과 같습니다.

function doWork(data) {
  return function(text) {
    // sample function to console log
    consoleToLog(data);
    consoleToLog(b);
  }
}

약속 및 텍스트 매개 변수에서 데이터에 액세스하기 위해 doWork에서 내부 함수를 반환하지 않으려면 어떻게해야합니까? 내부 기능을 피하는 트릭이 있습니까?



답변

다음 Function.prototype.bind과 같이 첫 번째 인수에 값이 전달 된 새 함수를 만드는 데 사용할 수 있습니다.

P.then(doWork.bind(null, 'text'))

다음으로 변경할 수 있습니다 doWork.

function doWork(text, data) {
  consoleToLog(data);
}

이제, text실제로 것 'text'doWorkdata약속에 의해 해결 값이됩니다.

참고 : 약속 체인에 거부 처리기를 연결했는지 확인하십시오.


작업 프로그램 : Babel의 REPL에 대한 라이브 카피

function doWork(text, data) {
  console.log(text + data + text);
}

new Promise(function (resolve, reject) {
    var a = 5;
    if (a) {
      setTimeout(function () {
        resolve(a);
      }, 3000);
    } else {
      reject(a);
    }
  })
  .then(doWork.bind(null, 'text'))
  .catch(console.error);


답변

아마도 가장 간단한 대답은 다음과 같습니다.

P.then(function(data) { return doWork('text', data); });

또는 태그가 지정되어 있으므로 ecmascript-6화살표 함수를 사용합니다.

P.then(data => doWork('text', data));

나는 이것이 가장 읽기 쉽고 쓰기에는 너무 많지 않다고 생각합니다.


답변

카레 사용하기.

var P = new Promise(function (resolve, reject) {
    var a = 5;
    if (a) {
        setTimeout(function(){
            resolve(a);
        }, 3000);
    } else {
        reject(a);
    }
});

var curriedDoWork = function(text) {
    return function(data) {
        console.log(data + text);
    }
};

P.then(curriedDoWork('text'))
.catch(
    //some error handling
);


답변

Lodash는이 정확한 것에 대한 좋은 대안을 제공합니다.

 P.then(_.bind(doWork, 'myArgString', _));

 //Say the promise was fulfilled with the string 'promiseResults'

 function doWork(text, data) {
     console.log(text + " foo " + data);
     //myArgString foo promiseResults
 }

또는 성공 함수가 하나의 매개 변수 (충족 된 약속 결과) 만 갖도록하려면 다음과 같이 활용할 수 있습니다.

P.then(_.bind(doWork, {text: 'myArgString'}));

function doWork(data) {
    console.log(data + " foo " + this.text);
    //promiseResults foo myArgString
}

이것은 함수 내의 컨텍스트에 첨부 text: 'myArgString'됩니다 this.


답변

이 질문에 대한 새로운 대답은 ‘this’를 자동으로 묶고 훨씬 더 읽기 쉬운 화살표 함수를 사용하는 것입니다. 다음과 같은 링크를위한 Google :
https://2ality.com/2016/02/arrow-functions-vs-bind.html

다음과 같이 텍스트를 설정할 수 있습니다. this.text = ‘text’P.then (data => doWork (data)); // doWork 내부의 this.text는 ‘text’로 평가됩니다.

이것은 위의 jib에 의해 제안되었으며 그 (또는 이것!)이 지금 받아 들여지는 대답이어야합니다.


답변