[英]How do I write a synchronous function with parameters as an asynchronous function (Javascript)?
Suppose I have the following code: 假设我有以下代码:
Synchronous Version: 同步版本:
var waitingToGetValue = heavyProcessingFunc (para1, para2);
response.send(waitingToGetValue);
I tried looking around but all I got were functions without parameter. 我尝试环顾四周,但所得到的只是没有参数的函数。
Asynchronous Attempt: 异步尝试:
heavyProcessingFunc(para1, para2, (function(waitingToGetValue){
response.send(waitingToGetValue);
});
I need to send the two parameters to the function. 我需要将两个参数发送给函数。 The function returns a value that I need to use to then send it to the response.
该函数返回一个我需要使用的值,然后将其发送到响应。
Does it even matter if I put it in a asynchronous format? 如果我以异步格式放置它,这是否有关系? Can anyone recommend me a video/source that easily explains the difference synchronous vs asynchronous: I read many material for the past few days and it just keep getting more confusing with promises, callbacks, and trying to access the values outside those functions.
谁能推荐给我一个视频/资源,轻松地解释同步与异步的区别:在过去的几天里,我阅读了许多材料,并且越来越使promise,callback和尝试访问这些函数之外的值更加混乱。
function heavyProcessingFunc(para1, para2, callback){ console.log('We have two params to work with', para1, para2); setTimeout(function(){// Simulating a long request callback("Now we send the response by calling the callback"); // This is waitingToGetValue },3000); } heavyProcessingFunc("para1", "para2", function(waitingToGetValue){ console.log(waitingToGetValue); // response.send(waitingToGetValue); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.