2016-09-10 1 views
1

js promise api를 사용하여 refractor에 중첩 된 IF가 많은 코드를 사용하는 방법을 이해하려고합니다. 로컬 스토리지에서 JSON 객체를 가져올 때js를 사용하는 방법 doom의 피라미드를 제거하는 약속

예는 정상적인 코드는

function $storage(key,default) { 
    let json = localStorage.getItem(key); 

    if(json === null) return default; 

    try{ // <-- need try catch in case value was not valid json object 
    json = JSON.parse(json); 
    } catch (e) { 
    json = default; 
    } 
    return typeof json === 'object' ? json : default; 
} 

이 코드의 일기 좋게가 좋지 않다처럼 보일 것이다. 그래서 내가 활용할 수있는 JS 약속 난 예외를 던질 수있는 방법을 캐치 할 수있는 그것을 잡은 있도록 내부에 다음

function $storage (key, default) { 
let ret; 

let promise = new Promise((y,n) => y(localStorage)) 
.then(ls => JSON.parse(ls.getItem(key))) 
.then(json => typeof json === 'object' ? json : HOW_TO_THROW_ERROR()) 
//on more validation step if needed 
.then(json => typeof json === 'object' ? json : HOW_TO_THROW_ERROR()) 
.then(valid_json => { return = valid_json }) 
.catch(error => { ret = default; console.warn('json invalid',e); }); 

return ret; 

} 

지금 내가 알고 싶은

로 재 작성 및 기본을 실행 할 수있다 생각?

내가 당신이 어떤 오류가 발생하는 키워드 throw를 사용할 수있는 자바 스크립트의 성능

답변

1

당신은 오류가 발생하는 Promise.reject()을 사용할 수

function $storage (key, default) { 
let ret; 

let promise = new Promise((y,n) => y(localStorage)) 
.then(ls => JSON.parse(ls.getItem(key))) 
.then(json => typeof json === 'object' ? json : Promise.reject("invalid json")) 
.then(valid_json => { return = valid_json }) 
.catch(err => { ret = default; console.warn(err.message); }); 

return ret; 

} 

를 내가 더 읽기 쉽고 관용적 다음 찾을 수 있지만.

function $storage(key,default) { 
    let json = localStorage.getItem(key); 
    if(json === null || typeof json !== 'object') json = default; 

    try{ 
    json = JSON.parse(json); 
    } catch (e) { 
    json = default; 
    } finally { 
    return json 
    } 
} 

확실한 비동기 계산을 위해 약속이 사용됩니다. 다른 용도로 사용하면 다른 프로그래머를 혼동시킬 수 있습니다.

+0

대안을 공유해 주셔서 감사합니다. 가독성 부족 이외의 첫 번째 예제를 사용하는 단점이 있습니까? –

0

을 낭비 오전 JS 약속의 유효 사용합니다. MDN에서 예 : 당신은 기본적으로 그냥 다음은, 구문 분석에 실패하는 경우 때문에, 자동 사로 잡았됩니다 할 수

throw "Error2"; // generates an exception with a string value 
throw 42;  // generates an exception with the value 42 
throw true;  // generates an exception with the value true 
throw new Error("Error"); 
0
function $storage (key, default) { 
let ret; 

let promise = new Promise((y,n) => y(localStorage)) 
.then(ls => JSON.parse(ls.getItem(key))) 
.then(json => typeof json === 'object' ? json : throw new Error("invalid json")) 
//on more validation step if needed 
.then(json => typeof json === 'object' ? json : throw new Error("invalid json")) 
.then(valid_json => { return = valid_json }) 
.catch(err => { ret = default; console.warn(err.message); }); 

return ret; 

} 

.

function $storage (key, default) { 
let ret; 

let promise = new Promise((y,n) => y(localStorage)) 
.then(ls => JSON.parse(ls.getItem(key))) 
.then(valid_json => { return = valid_json }) 
.catch(err => { ret = default; console.warn(err.message); }); 

return ret; 

} 
+0

문제는 $ storage는 항상 undefined를 반환합니다. 함수가 값 – Zalaboza

+0

을 반환 한 후에 약속이 해결 되었기 때문에 대신 약속을 반환하고 호출 함수에서'then()'체인을 수행 할 수 있다고 생각합니다. 약속은 나중에 해결 될 것이므로 동기 반환은 어떤 경우에도 작동하지 않습니다. – tedcurrent

1

당신은 발생한 오류에 던져 다음 캐치 방법

var p1 = new Promise(function(resolve, reject) { 
    resolve('Success'); 
}); 

p1.then(function(value) { 
    console.log(value); // "Success!" 
    throw 'oh, no!'; 
}).catch(function(e) { 
    console.log(e); // "oh, no!" 
}).then(function(){ 
    console.log('after a catch the chain is restored'); 
}, function() { 
    console.log('Not fired due to the catch'); 
}); 

// The following behaves the same as above 
p1.then(function(value) { 
    console.log(value); // "Success!" 
    return Promise.reject('oh, no!'); 
}).catch(function(e) { 
    console.log(e); // "oh, no!" 
}).then(function(){ 
    console.log('after a catch the chain is restored'); 
}, function() { 
    console.log('Not fired due to the catch'); 
}); 

에서 그들을 처리하지만, 비동기 기능에 약간의 오차가 발생하는 경우 캐치는 호출되지 않습니다 사용할 수 있습니다. 소스

// Errors thrown inside asynchronous functions will act like uncaught errors 
var p2 = new Promise(function(resolve, reject) { 
    setTimeout(function() { 
    throw 'Uncaught Exception!'; 
    }, 1000); 
}); 

p2.catch(function(e) { 
    console.log(e); // This is never called 
}); 

:

function safeParse(x) { 
    try { 
     return JSON.parse(x); 
    } catch(e) { 
     // Log the problem 
     return null; 
    } 
} 

function parmval(key, defval) { 
    var json = safeParse(localStorage.get(key)); 
    return (typeof json === "object") ? json : defval; 
} 

약속은 비동기 작업하지 IF를 대해 수 있습니다 : 내가 볼 문제는 더 사용할 수있는 기능에 포장, 막 JSON.parse입니다 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch

0

당신이 뭔가를 얻을 .

관련 문제