Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

js异步return

有点理不清异步return的逻辑,b函数里把a函数的返回值打印,a函数的返回值是异步得到的,所以一开始会得到空数组,怎么修改能使得data不为空之后再return出来呀

        function a(){
            console.log('a');
            var data=[];
            setTimeout(function (){
                data.push([1]);
            },1000);
            return data;
        }
        
        function b(){
            console.log('b');
            var d=a();
            console.log(d);
        }

        b();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

用回调函数通知或者使用 async function

function getData(callback) {
  const data = []
  console.info(data)
  setTimeout(_ => {
    data.push(+new Date())
    typeof callback === 'function' && callback(data)
  }, 1e3)
}

getData(data => console.info(data))
async function getData() {
  const sleep = delay => new Promise(resolve => setTimeout(resolve, delay || 0))
  const data = []
  console.info(data)
  await sleep(1000)
  data.push(+new Date())
  return data
}

;(async _ => {
  console.info(await getData())
})()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...