如何阻止在异步的JavaScript功能 [英] How to block on asynchronous functions in JavaScript

查看:96
本文介绍了如何阻止在异步的JavaScript功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用JavaScript编写一个函数,它从调用异步函数返回一个状态。然而,主叫方只接收值并没有回调函数将被提供。我想是这样的:

I need to write a function in JavaScript, which returns a state from calling an asynchronous function. However, the caller only receives the value and no callback function is to be provided. I tried something like:

function getState() {
    var ret = null;
    asyncCall("request",
        function() { ret = "foo"; } // callback
    );
    while (ret === null)
        ; // block on the asynchronous call
    return ret;
}

然而,循环永远不会结束......

However, the loop is never going to end…

任何想法?谢谢你。

推荐答案

我认为你正在寻找StratifiedJS, http://stratifiedjs.org
它可以让你编排的异步code完全像你写,小心它写像同步code,它不会阻止应用程序的其余部分。
您可以通过加载阿波罗JS库的任何地方使用它。

I think you're looking for StratifiedJS, http://stratifiedjs.org It allows you to "orchestrate" your async code exactly like you wrote, BEWARE that it "writes" like synchronous code, it will NOT block the rest of your application. You can use it anywhere by loading the apollo js library.

这是它会是什么样子在分层的JavaScript:

This is how it would look like in Stratified JavaScript:

function getState() {
  waitfor (var ret) {
    // block on the asynchronous call
    asyncCall("request", resume);
  }
  return ret;
}

当然也有模块/库,只会使它看起来像这样:
http://onilabs.com/modules#http

function getState() {
  return http.get("request");
}

这篇关于如何阻止在异步的JavaScript功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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