简体   繁体   English

如何编写带有参数的同步函数作为异步函数(Javascript)?

[英]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.

相关问题 如何从头开始用Javascript编写异步Map函数? - How do I write an asynchronous Map function in Javascript from scratch? 如何将异步(基于回调)函数的执行包装到Javascript中的同步函数中? - How do I wrap executions of asynchronous (callback-based) functions into a synchronous function in Javascript? 通常,在Javascript中,如何使异步函数同步? - In Javascript, generally, how to make asynchronous function synchronous? 如何使异步javascript函数同步 - how to make an asynchronous javascript function synchronous JavaScript:可恢复为同步的异步功能 - JavaScript: asynchronous function that resumes to synchronous 在JavaScript中异步函数的末尾运行同步函数? - Run synchronous function at the end of an asynchronous function in JavaScript? 我怎样才能使ahoy的javascript异步函数轨道同步 - How can I make ahoy's javascript asynchronous function track synchronous 如何知道 node.js 中的函数是异步的还是同步的? - How do you know if a function is asynchronous or synchronous in node.js? 使异步功能以同步方式运行-Javascript - Make asynchronous function to run as synchronous - Javascript 有异步函数调用时的Javascript同步流 - Javascript synchronous flow when there are asynchronous function call
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM