从javascript函数返回一个值,然后在其中执行代码

时间:2017-05-04 19:51:36

标签: javascript asynchronous browser settimeout setinterval

我有一个javascript函数需要返回true才能更新浏览器UI。如何在执行代码之前确保函数返回以进行后端调用?

Test: {
    name: String,
    subField: {
        name: String,
        ref: {type: ObjectId, ref: "Test"}
    }
}

2 个答案:

答案 0 :(得分:2)

我想你在self.backendCall(XHR / fetch)中有一个ajax请求

如果确实如此,那么您的代码已经异步

否则,请看@hemp的回答

function ajax(){
  fetch("https://httpbin.org/get").then(data=>{
    console.log("DONE")
  })
}

function test(){
  ajax();
  return true;
}

console.log(test())

答案 1 :(得分:2)

假设浏览器JS,你可以普遍使用setTimeout,这将保证当前的代码路径在backendCall代码执行之前完成,但是它没有说明什么时候(除非你指定一个超时期限。)

self.resortCopy = function(item) {
self.resorts.push(item);
window.setTimeout(self.backendCall.bind(self, item), 0);
return true;