首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VSS行为异步

VSS行为异步
EN

Stack Overflow用户
提问于 2020-07-06 17:22:29
回答 2查看 115关注 0票数 0

我有这段代码

代码语言:javascript
复制
    VSS.require(["TFS/WorkItemTracking/Services"], function(workItemServices:any) {
        workItemServices.WorkItemFormService.getService().then(function (workItemFormSvc:any) {             
            if(workItemFormSvc.hasActiveWorkItem()) {
                workItemFormSvc.getFieldValue(["System.Id"]).then(function(value:any){
                    wId = value;
                    console.log("work item id",value);
                });
            }
            else {
                console.log("Active work item is NOT available.");
            }
        });
    });

    VSS.require(["VSS/Service"], function() {
        userId = VSS.getWebContext().user.id;
        console.log("inside require::::", VSS.getWebContext().user.id);
    });     

    this.setState({workItemId : wId}, ()=>console.log(this.state.workItemId));
    this.setState({personId : userId}, ()=> console.log(this.state.personId));

console.log输出如下

红矩形的是this.setState的,绿框的是require的。

我希望有这个值,但是在从require作用域设置值之前,赋值操作就已经完成了。

我怎么能处理这事?

注意:在正式文档中表示require()是异步的

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-07 13:28:49

我必须在构造函数处绑定函数,然后将this存储为refThis,就在require()块之前

代码语言:javascript
复制
constructor(props:any){
        
    super(props);
    this.getIds = this.getIds.bind(this);
}

getIds(){
        
    var refThis = this;
    VSS.require(["TFS/WorkItemTracking/Services"], function(workItemServices:any) {

        //get workItemId
        workItemServices.WorkItemFormService.getService().then(function(workItemFormSvc:any) {              
            if(workItemFormSvc.hasActiveWorkItem()) {
                workItemFormSvc.getFieldValue(["System.Id"]).then(function(value:any){
                    // Is there a problem with the following line ? (loadData() has to work after id is assigned)
                    refThis.setState({id:value}, () =>{ refThis.loadData() });
                });
            }
        }));    
    });
}
票数 0
EN

Stack Overflow用户

发布于 2020-07-07 10:04:01

setState中的console.log之前,您需要使用require()。例如:

代码语言:javascript
复制
    VSS.require(["TFS/WorkItemTracking/Services"], function(workItemServices:any) {
    workItemServices.WorkItemFormService.getService().then(function (workItemFormSvc:any) {             
        if(workItemFormSvc.hasActiveWorkItem()) {
            workItemFormSvc.getFieldValue(["System.Id"]).then(function(value:any){
                wId = value;
                this.setState({workItemId : wId}, ()=>console.log(this.state.workItemId));
                console.log("work item id",value);
            });
        }
        else {
            console.log("Active work item is NOT available.");
        }
    });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62761284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档