为什么不是我的未来价值现已上市? [英] Why isn't my future value available now?

查看:115
本文介绍了为什么不是我的未来价值现已上市?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Ajax调用没有返回任何东西!这里是我的code:

My ajax call is not returning anything! Here is my code:

var answer;
$.getJSON('/foo.json') . done(function(response) { answer = response.data; });
console.log(answer);

即使网络电话正在取得成功,我可以看到,响应包含数据,控制台日志未定义!这是怎么回事?

Even though the network call is succeeding, and I can see that the response contains data, the console logs "undefined"! What is happening?

推荐答案

我们发现自己处于这似乎沿着我们所说的时间维度进步宇宙。我们真的不知道是什么时候,但是我们已经制定的抽象和词汇,让我们有理由谈谈这件事。之后前过去,present,未来,

We find ourselves in a universe which appears to progress along a dimension we call "time". We don't really understand what time is, but we have developed abstractions and vocabulary that let us reason and talk about it: "past", "present", "future", "before", "after".

计算机系统我们建立 - 越来越多 - 有时间作为一个重要的维度。有些事情是建立在未来发生。然后其他的事情需要发生后的第一件事情最终会发生。这是被称为不同步的基本概念。在我们这个日益网络化的世界,asynchonicity的最常见的情况是等待一些远程系统以响应某些要求。

The computer systems we build--more and more--have time as an important dimension. Certain things are set up to happen in the future. Then other things need to happen after those first things eventually occur. This is the basic notion called "asynchronicity". In our increasingly networked world, the most common case of asynchonicity is waiting for some remote system to response to some request.

考虑一个例子。你叫送奶工和订购一些牛奶。当它来临的时候,你希望把它放在你的咖啡。你不能把牛奶在你的咖啡,现在,因为它不是在这里呢。你必须等待它把它在你的咖啡之前。换句话说,以下将不起作用:

Consider an example. You call the milkman and order some milk. When it comes, you want to put it in your coffee. You can't put the milk in your coffee right now, because it is not here yet. You have to wait for it to come before putting it in your coffee. In other words, the following won't work:

var milk = order_milk();
put_in_coffee(milk);

由于JS没有办法知道它需要为 order_milk 来完成它之前执行 put_in_coffee 。换句话说,它不知道 order_milk 异步 - 是不会导致牛奶,直到将来的某个时间的东西。 JS和其他声明性语言,执行了一个又一个声明,而无需等待。

Because JS has no way to know that it needs to wait for order_milk to finish before it executes put_in_coffee. In other words, it does not know that order_milk is asynchronous--is something that is not going to result in milk until some future time. JS, and other declarative languages, execute one statement after another without waiting.

经典的JS办法处理这一问题,采取的是JS支持功能,作为可以传递第一类对象,事实的优点是通过一个函数作为参数传递给asynchonous请求,它将然后调用时它具有完成其任务在将来某个时候。这是回调的方法。它看起来是这样的:

The classic JS approach to this problem, taking advantage of the fact that JS supports functions as first-class objects which can be passed around, is to pass a function as a parameter to the asynchonous request, which it will then invoke when it has complete its task sometime in the future. That is the "callback" approach. It looks like this:

order_milk(put_in_coffee);

order_milk 揭开序幕,订购牛奶,那么,当且仅当它到来时,它调用 put_in_coffee

order_milk kicks off, orders the milk, then, when and only when it arrives, it invokes put_in_coffee.

这个回调方法的问题是,它污染功能的正常语义报告其结果与收益;相反,功能必须NOST通过调用作为参数的回调报告他们的结果。此外,随着事件的较长序列打交道时,这种方法能迅速变得难以处理。例如,让我们说,我要等待要放牛奶咖啡,然后才把执行第三步,即饮咖啡。我最终需要这样写:

The problem with this callback approach is that it pollutes the normal semantics of a function reporting its result with return; instead, functions must nost reports their results by calling a callback given as a parameter. Also, this approach can rapidly become unwieldy when dealing with longer sequences of events. For example, let's say that I want to wait for the milk to be put in the coffee, and then and only then perform a third step, namely drinking the coffee. I end up needing to write something like this:

order_milk(function(milk) { put_in_coffee(milk, drink_coffee); }

我在哪里传递给 put_in_coffee 这两个牛奶放在它,也是行动( drink_coffee )要执行一次牛奶已经投入,这样的code变得难以写,读,和调试。

where I am passing to put_in_coffee both the milk to put in it, and also the action (drink_coffee) to execute once the milk has been put in. Such code becomes hard to write, and read, and debug.

在这种情况下,我们可以把code中的问题为:

In this case, we could rewrite the code in the question as:

var answer;
$.ajax('/foo.json') . done(function(response) {
  callback(response.data);
});

function callback(data) {
  console.log(data);
}

输入承诺

这是一个承诺,这是值重新$ P $一个特定类型的概念动机psents一个未来同步的一些结果分类。它可以重新present事情已经发生,或会在未来发生,也可能根本就不会发生。承诺有一个方法,名为然后,到传递时结果的承诺,重新presents已经实现了将要执行的操作。

Enter promises

This was the motivation for the notion of a "promise", which is a particular type of value which represents a future or asynchronous outcome of some sort. It can represent something that already happened, or that is going to happen in the future, or might never happen at all. Promises have a single method, named then, to which you pass an action to be executed when the outcome the promise represents has been realized.

在我们的牛奶和咖啡的情况下,我们设计 order_milk 来返回到达,然后指定牛奶的承诺 put_in_coffee 然后操作,如下所示:

In the case of our milk and coffee, we design order_milk to return a promise for the milk arriving, then specify put_in_coffee as a then action, as follows:

order_milk() . then(put_in_coffee)

这样做的好处是,我们可以串这些结合在一起创造未来发生的序列(链接):

One advantage of this is that we can string these together to create sequences of future occurrences ("chaining"):

order_milk() . then(put_in_coffee) . then(drink_coffee)

让我们承诺适用于您的特定问题。最后,我们将一个函数,该函数返回一个承诺内我们请求逻辑:

Let's apply promises to your particular problem. We will wrap our request logic inside a function, which returns a promise:

function get_data() {
  return $.ajax('/foo.json');

loadFile: function(file) {
    //get the json object
    return $.getJSON("/" + Language.language + "/lang/" + file, function( data ) {
        //go through each item in the json object and add it to the 
        $.each( data, function( key, val ) {
            console.log(key+":"+val);
            Language.words[key]=val;                //add the word
        });
    });
},

其实,我们所做的加入 A 返回调用 $。阿贾克斯。这工作,因为jQuery的 $。阿贾克斯已返回一种承诺性的东西。 (在实践中,并没有涉及到的详细信息,我们将preFER来包装这个调用,从而返回一个真正的承诺,或者使用一些替代 $。阿贾克斯是这样做)。现在,如果我们要加载的文件,并等待它完成,然后做一些事情,我们可以简单地说

Actually, all we've done is added a return to the call to $.ajax. This works because jQuery's $.ajax already returns a kind of promise-like thing. (In practice, without getting into details, we would prefer to wrap this call so as return a real promise, or use some alternative to $.ajax that does so.) Now, if we want to load the file and wait for it to finish and then do something, we can simply say

get_data() . then(do_something)

例如,

get_data() . 
  then(function(data) { console.log(data); });

在使用的承诺,我们最终经过大量的功能集成到然后,所以它往往有助于使用更紧凑的ES6式箭头功能:

When using promises, we end up passing lots of functions into then, so it's often helpful to use the more compact ES6-style arrow functions:

get_data() . 
  then(data => console.log(data));

异步关键字

但还是有一些隐约约不满意,如果有同步和一个完全不同的方式,如果异步写code的一种方式。对于同步,我们写

The async keyword

But there's still something vaguely dissatisfying about having to write code one way if synchronous and a quite different way if asynchronous. For synchronous, we write

a();
b();

但如果 A 是异步的,与我们在写承诺

but if a is asynchronous, with promises we have to write

a() . then(b);

上面,我们说,JS没有办法知道它需要的作为第一次调用完成它执行前一秒。那岂不是很好,如果有某种方式告诉JS呢?事实证明,有就是 - 的await 关键字,一种特殊类型的函数内部使用的称为异步功能。此功能是ES的未来版本的一部分,但在transpilers如通天给予正确的preset中已经可用。这让我们简单地写

Above, we said "JS has no way to know that it needs to wait for the first call to finish before it executes the second". Wouldn't it be nice if there was some way to tell JS that? It turns out that there is--the await keyword, used inside a special type of function called an "async" function. This feature is part of the upcoming version of ES, but is already available in transpilers such as Babel given the right presets. This allows us to simply write

async function morning_routine() {
  var milk   = await order_milk();
  var coffee = await put_in_coffee(milk);
  await drink(coffee);
}

在你的情况,你就可以写类似

In your case, you would be able to write something like

async function foo() {
  data = await get_data();
  console.log(data);
}

这篇关于为什么不是我的未来价值现已上市?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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