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