如何让TypeScript中DoSomeThing2在DoSomeThing1完成后执行(C# MVC场景)
问题解决方法
错误原因
你当前的代码直接执行了DoSomeThing2(userid, city, address),并把它的返回值(void)传给了.done()方法。但.done()需要接收的是回调函数(而非函数执行后的结果),这就导致了TS2345类型不匹配错误。
修复方案
方案1:用箭头函数包裹回调
通过匿名箭头函数延迟DoSomeThing2的执行,确保它在DoSomeThing1的异步请求完成后才被调用,同时保留当前上下文的this:
this.DoSomeThing1(userid, city, address) .done(() => { this.DoSomeThing2(userid, city, address); });
方案2:使用.then()链式调用
如果DoSomeThing1返回的是jQuery Deferred/jqXHR对象,也可以用.then()实现顺序执行(.then()和.done()功能类似,但支持链式返回新的异步操作):
this.DoSomeThing1(userid, city, address) .then(() => this.DoSomeThing2(userid, city, address));
关键前提:确保DoSomeThing1返回异步请求对象
必须保证DoSomeThing1方法返回jQuery Ajax请求的结果(jqXHR对象),这样才能调用.done()/.then()方法。示例如下:
DoSomeThing1(userid: string, city: string, address: string): JQueryXHR { // 返回serviceBase.Service发起的Ajax请求结果 return serviceBase.Service({ url: '/YourController/GetBackend', method: 'GET', data: { userid, city, address } }); }
内容的提问来源于stack exchange,提问作者Amatour__
相关产品推荐
相关产品推荐

