如何重写此异步方法以同步返回值? [英] How to rewrite this asynchronous method to return the value synchronously?

查看:58
本文介绍了如何重写此异步方法以同步返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于使Nodejs/Javascript方法同步有很多问题,但是到目前为止,我看到的答案涉及到使用 async fibrous 之类的库.

There are many questions on making a Nodejs/Javascript method synchronous, but the answers I have seen so far involved using libraries such as async and fibrous.

但是要使用 fibrous 之类的库,我必须使用其包装器包装函数.

But to use libraries such as fibrous, I have to wrap my function with their wrapper.

我正在寻找一种解决方案,其中代码位于我的函数之内(而不是在函数内部并包装).

I am seeking a solution where the code lies within my function (not outside and wrapping it).

例如,这是我的使用回调的异步函数:

For example, this is my async function which uses a callback:

function myFunc(callback) {
  // Classic database fetch which is asynchronous
  db.find("foo", function(err, results) {
    callback(err, results);
  });
}

我想要的是该函数返回结果:

What I want is for the function to return the results:

function myFunc() {
  // Make this function synchronous, and return the result
  // ...

  return results;
}

我该怎么做?

再一次,我不想将 myFunc 与其他功能包装在一起.我在想睡眠循环是否起作用?

Once again, I don't want to wrap myFunc with other functions. I am thinking if a sleep loop works?

推荐答案

不,您不能使用循环来等待异步调用.Javascript是单线程的,因此您需要将控制权返回给主事件处理程序,以便调用异步回调.如果运行循环,则数据库查询完成的事件将仅在队列中等待,而永远不会被处理.

No, you can't use a loop to wait for an asynchronous call. Javascript is single threaded, so you need to return control to the main event handler for the asynchronous callback to be called. If you run a loop, the event that the database query is completed will just wait in the queue and never be handled.

您可以做的是返回承诺而不是结果本身.该对象可以跟踪是否已调用了回调函数,具有一个可以在其中放置结果的回调函数的属性,并具有在需要时获取结果的方法(使用回调函数,因为一旦使用异步方法,因此无法完全同步处理.)

What you can do is to return a promise instead of the result itself. That's an object that keeps track of whether the callback has been called or not, has a property where the callback can put the result, and has a method for getting the result when you need it (which uses a callback, because once you use an asynchrous method it can't be handled completely syncronously).

这篇关于如何重写此异步方法以同步返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆