JS 異步查詢返回為undefined


1.只有一個異步函數時,可以對改方法使用then獲取返回數據

//孫子函數
function grandChild() {
let p = new Promise((resolve) => {
setTimeout(function() {
resolve('孫子')
}, 500)
})
return p
}

//兒子函數
function child(item) {
let p = new Promise((resolve) => {
setTimeout(function() {
resolve('兒子' + item)
}, 700)
})
return p
}

 

2.在一個函數中使用2個嵌套的異步函數,不能通過then獲取返回數據,會報錯,需要在第一個函數名之前添加return,將2個嵌套函數都返回就不會報錯了

//錯誤的寫法
//在函數finalFunc中定義2個嵌套異步函數,即在一個異步函數的then中再調用一個異步函數
function finalFunc() {
grandChild().then(e => {
return child()
}) //這里必須要有return返回這個函數
}

//使用finalFun
finalFunc().then(e => {
console.log(e) //會報錯,報finalFunc.then是undefined,因為嵌套的異步函數是再then中使用,不能被finalFunc函數的外部使用,所以會報錯
})

//正確寫法

function finalFunc() {
return grandChild().then(e => { //這個return必須存在,否則不會輸出數據
return child()
}) //這里必須要有return返回這個函數
}

//使用finalFun
finalFunc().then(e => {
console.log(e) //輸出 ‘孫子兒子’
})

3.使用await和async

//await是將異步轉換為同步,即必須等上一步執行完之后才會執行下一步,await需要與async一起搭配使用,
//async標志函數是異步函數,函數返回的Promise對象,需要通過then獲取數據
async function finalFunc() {
let datagrandChild = await grandChild()
let datachild = await child()
return (datafather + datagrandChild)
}

//使用finalFunc()
finalFunc().then(e => {
console.log(e) //輸出‘孫子兒子’
})

4.使用callback回調函數

//給函數一個callback函數作為函數的參數
function finalFunc(callback) {
grandChild().then(g => {
//在孫子函數的回調方法中調用兒子函數
child(g)
}).then( c => {
//在兒子函數的回調方法中調用callback回調函數
callback(c)
})
}

//使用finalFunc()函數
finalFunc(e => {
console.log(e) //輸出‘兒子孫子’
})

————————————————
原文鏈接:https://blog.csdn.net/weixin_40509884/article/details/100542809


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM