问题描述
javascript 有两个函数,第1个内有ajax,第2个根据函数1返回的数据处理后再返回新的数据,以下代码返回的是NaN
相关代码
// 重后台获取数据,根据pid返回不同的数据,例如返回的10
var cloth = function(pid){
$.get('api/cds?pid='+pid,function(data){
return data;
});
}
// 处理数据 cloth()返回的数据后,返回新的数据
var clothData = function(pid,thisId){
return cloth(pid) + thisId;
}
console.log(clothData(1,10));
你期待的结果是什么?实际看到的错误信息又是什么?
clothData 返回的是20
因为 clothSelect 函数没有 return 返回值,默认为 undefined
像下面这样,用 return 返回,就不会为 undefined
如果要获取 ajax 返回的数据,可以使用下面几种方式
第一种方式
第二种方式
更多方式,比如自己定义回调函数传入,或者包装成 Promise,然后更进一步用 async