나는 자바 스크립트를 처음 접했고 함수 실행을 연결해야하지만 성공과 실패에 반응하는 기능이 다릅니다. 함수 배열은 매개 변수로 가져오고 이전 결과는 성공시 다음 체인에 대한 입력 매개 변수이며 오류가 발생하면 경고 / 로그 동작을 정의 할 수 있습니다. 나는 jquery가 GET ajax 메소드 성공과 실패에 대한 예를 들어주는 방식을 좋아합니다. 내부 함수가 해당 이벤트를 발생시키는 방법, 이것이 자바 스크립트에서 어떻게 구현됩니까?
여기 에서 두 솔루션의 라이브 데모를 확인 하십시오 (클릭).
이제 Promise는 콜백이 아닌 최선의 접근 방식으로 간주됩니다. 콜백은 시작하기 쉽고 나중에 약속에 대해 이야기하는 것이 더 쉽기 때문에 시작하겠습니다.
//change this to true or false to make the function "succeed" or "fail"
//var flag = false;
var flag = true;
//this is the function that uses "success" and "error"
function foo(params) {
//some condition to determine success or failure
if (flag) {
//call the success function from the passed in object
params.success();
}
else {
//call the error function from the passed in object
params.error();
}
}
//function "foo" is called, passing in an object with success and error functions
foo({
success: function() {
console.log('success!');
},
error: function() {
console.log('error!');
}
});
완전한 솔루션의 경우 해당 속성을 호출하기 전에 해당 속성이 존재하는지 확인해야합니다. 성공 및 오류 함수가 전달 된 경우에만 호출하십시오.
그렇게하는 방법은 다음과 같습니다.
if (flag) {
//the function is only fired if it exists
params.success && params.success();
}
개체에 전달할 필요가 없습니다. 함수가 개별 매개 변수를 받아들이도록 할 수 있습니다.
function foo(success, error) {
if (flag) {
success && success();
}
else {
error && error();
}
}
foo(
function() {
console.log('success!');
},
function() {
console.log('error!');
}
);
함수가 전달 된 내용을 기반으로 객체의 개별 매개 변수 또는 함수를 사용하도록 할 수도 있습니다. 첫 번째 매개 변수가 함수인지 객체인지 확인하고 그에 따라 사용하면됩니다.
function foo(success, error) {
if (arguments.length === 1 && typeof arguments[0] === 'object') {
var params = arguments[0];
success = params.success;
error = params.error;
}
if(flag) {
success && success();
}
else {
error && error();
}
}
foo(function() {
console.log('success');
});
foo({
success: function() {
console.log('success!');
}
});
내가 말했듯이, 나는 비동기 함수를 다루는 데 매우 좋은 promise를 사용하는 것을 매우 선호합니다. 이를 위해서는 promise 라이브러리 또는 ES6 JavaScript가 필요합니다. 이것이 jQuery로 보이는 방식입니다. 대부분의 라이브러리는 유사합니다.
function bar() {
var deferred = new $.Deferred();
if (flag) {
//if you resolve then, the first "then" function will fire
deferred.resolve();
}
else {
//if you reject it, the second "then" function will fire
deferred.reject();
}
return deferred.promise();
}
//since "bar" returns a promise, you can attach a "then" function to it
//the first function will fire when the promise is resolved
//the second function will fire when the promise is rejected
bar().then(function() {
console.log('bar success!');
},
function() {
console.log('bar error!');
});
JavaScript ES6 Promise 사용 :
function bar() {
return new Promise(function(resolve, reject) {
if (flag) {
resolve()
}
else {
reject();
}
})
}
약속은 처음에는 이해하기 어려울 수 있습니다. 머리를 감싸는 데 도움이되는 좋은 튜토리얼이 많이 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다