js setTimeout 中怎么返回值

https://img2.mukewang.com/5c7f31430001846e08000184.jpg

由于DOM加载问题,需要异步后才能获取到DOM的属性, 但是我需要返回这个判断, 怎么写才能返回出去判断后的值;

代码如下,现在是不行的


 checkOver(item){

        let check = false;

          setTimeout(() => {

            check = $('#dept' + item.department_id)[0].offsetWidth < $('#dept' + item.department_id)[0].scrollWidth;

            return check;

          }, 1)

      }


慕码人2483693
浏览 3628回答 2
2回答

慕盖茨4494581

在setTimeout中你是拿不到返回值的,你可以用Promise来wrap一下。function checkOver(item) {&nbsp; &nbsp;let check = false;&nbsp; &nbsp;let promise = new Promise(function(resolve, reject) {&nbsp; &nbsp; &nbsp;setTimeout(() => {&nbsp; &nbsp; &nbsp; &nbsp;check = $('#dept' + item.department_id)[0].offsetWidth < $('#dept' + item.department_id)[0].scrollWidth;&nbsp; &nbsp; &nbsp; &nbsp;resolve(check);&nbsp; &nbsp; &nbsp;}, 1);&nbsp; &nbsp;});&nbsp; &nbsp;return promise;}checkOver(item).then((check) => {&nbsp; console.log(check); // --> true/false});

慕工程0101907

异步返回不出去的&nbsp;关于异步常用两种方式 callback和promisecallback回调:checkOver(item,callback){&nbsp; &nbsp; let check = false;&nbsp; &nbsp; setTimeout(() => {&nbsp; &nbsp; &nbsp; &nbsp; check = $('#dept' + item.department_id)[0].offsetWidth < $('#dept' + item.department_id)[0].scrollWidth;&nbsp; &nbsp; &nbsp; &nbsp; callback&&callback(check)&nbsp; &nbsp; }, 1)}//调用checkOver(item,function(check){&nbsp; &nbsp; console.log(check)})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript