在使用axios时在.then外部访问变量(在for循环内部)

时间:2019-05-28 10:54:00

标签: javascript scope

const getUser = (user) => {
    var dataArray = [];
    var previous_epoch; 

    var utc = new Date()
      .toJSON()
      .slice(0, 10)
      .replace(/-/g, "/"); 

    for (let i = 0; i <= 5; i++) {       


     if(i == 0 ){
        console.log('0');
         previous_epoch = new Date(utc).getTime() / 1000;
     }    
     else {
         previous_epoch = new Date(utc).getTime() / 1000;
         console.log('else',dataArray); <--- always returns empty array
     }
     console.log(getdat);
    getdat(user,previous_epoch).then((resp) => {
        let jsondat = resp.data.data;
        dataArray = jsondat.concat(dataArray);
        console.log('dat',dataArray); <---shows the right data here
       })
    }


}

我在 getdat 函数外部声明了一个空数组dataArray,该数组用于获取数据并将其推入dataArray。

但是当我尝试在.then函数之外访问它时,它总是显示为空

编辑

function getdat(user,epoch)
{
    const sub_url = `https://api.pushshift.io/reddit/search/submission/?subreddit=${user}&limit=1000&sort=desc&before=`;
    return  axios.get(sub_url + epoch)
}

0 个答案:

没有答案