简体   繁体   English

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

[英]return a value from javascript function and then execute code inside it

I have a javascript function which needs to return true in order to update the browser UI. 我有一个javascript函数,该函数需要返回true才能更新浏览器UI。 How can I make sure the function returns before executing the code to make a backend call? 在执行代码进行后端调用之前,如何确保函数返回?

 self.resortCopy = function(item) {
 self.resorts.push(item);
 self.backendCall(item) // this needs to be performed after returning true
 return true;

I imagine you are having a ajax request inside self.backendCall (XHR/fetch) 我想象你在self.backendCall(XHR / fetch)中有一个Ajax请求

If that is true, then your code already async 如果是这样,则您的代码已经异步

Else, look at @hemp's answer 否则,看看@hemp的答案

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

Assuming browser JS, you can use setTimeout universally, this will guarantee that the current codepath finishes before the backendCall code executes, but it doesn't say anything else about when (unless you specify a timeout period.) 假设使用浏览器JS,则可以通用地使用setTimeout,这将确保当前代码路径在backendCall代码执行之前完成,但不会说明何时(除非您指定超时时间)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM