我需要在JavaScript中编写一个函数,它从调用异步函数返回一个状态.但是,调用者只接收该值,并且不提供回调函数.我尝试过类似的东西:
function getState() {
var ret = null;
asyncCall("request",
function() { ret = "foo"; } // callback
);
while (ret === null)
; // block on the asynchronous call
return ret;
}
Run Code Online (Sandbox Code Playgroud)
然而,循环永远不会结束......
有任何想法吗?谢谢.
如果在转换之前完成ajax,我需要显示微调器至少2秒.
我有以下但不工作
route: {
data(transition) {
this.getDelayedData();
transition.next();
}
},
methods:{
getSliders(){
this.$http.get('/api/sliders/getsliders')
.then(sliders =>{this.sliders = sliders.data
});
},
getPosts(){
this.$http.get('/api/posts/getposts')
.then(posts =>{this.posts = posts.data.data
});
},
getDelayedData(){
function timer() {
var dfd = $.Deferred();
setTimeout(function()
{
console.log("done");
}, 2000,dfd.resolve);
return dfd.promise();
}
$.when( this.getPosts(), this.getSliders(),timer() )
.done();
}
}
Run Code Online (Sandbox Code Playgroud)
我试图实现读这篇文章的代码但是$ .when函数不会等到setTimeout函数执行完毕.