前言
異步操作對於前端開發而言必不可少,尤其和后端進行交互的時候,項目有時需要多個異步操作串聯來進行運算,而我們通常會選擇把其封裝起來作為公用的方法,此時便要return返回值。
問題
function getProm() { return Promise.resolve(ajax_method()).then(res=>{ return res; }); }//Promise { <pending> }
這個時候獲取到的是Promise的方法體,其內部的[[PromiseValue]]是不對外開放的,就是我們無法從方法體外部獲取這個值,這里就算換成async也一樣。
解決
無法從外部獲取就從內部解決,在到最后的方法之前,我們依然返回整個Promise的方法體,到了最后需要展示或使用到請求體的內的數據時,再利用.then獲取。
function ajax_method() { let str = ' World '; return getProm2().then(data=>{ str = data + str; return str; }) } function ajax_method2(url,data,method,success) { return ' Hello '; } function getProm() { return Promise.resolve(ajax_method()).then(res=>{ return res; }); }//Promise { <pending> } function getProm2() { return Promise.resolve(ajax_method2()).then(res=>{ // console.log(res); return res; }); } function getFunc(){ let str = ''; return getProm().then(data=>{ return str + data; }) return str; } console.log(getFunc());//Promise { <pending> } getFunc().then(data=>console.log(data));//Hello World
總結
今天講的思路比較簡單,相信大部分人都知道,只是剛巧有人問起我就講解了一下,此外大家要注意,異步體內可以進行try catch判斷以及.then().then().finally()等鏈式操作。
async fetchData(url) => { try { const response = await axios.get(`/q?query=${query}`) const data = response.data this.props.processfetchedData(data) } catch (error) { console.log(error) } }
Promise.resolve(ajax_method()) .then(console.log('成功')) .catch(error => console.error(error)) .finally(() => console.log('結束'))