如何承诺在JavaScript中工作吗? [英] How do promises work in JavaScript?

查看:154
本文介绍了如何承诺在JavaScript中工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是实现返回根据AngularJS另一个承诺一个承诺我的第一个功能,它的工作。但在此之前,我决定的只是的做到这一点,我花了2小时来阅读,并试图了解背后的承诺的概念。我想,如果我可以写一段简单code,它模拟的承诺是如何工作的,我会再能概念的理解,而不是能够使用它没有真正了解它是如何工作。我不能写code。

I just implemented my first function that returns a promise based on another promise in AngularJS, and it worked. But before I decided to just do it, I spent 2 hours reading and trying to understand the concepts behind promises. I thought if I could write a simple piece of code that simulated how promises worked, I would then be able to conceptually understand it instead of being able to use it without really knowing how it works. I couldn't write that code.

所以,可能有人请香草JavaScript的说明承诺是如何工作的?

So, could someone please illustrate in vanilla JavaScript how promises work?

推荐答案

一个承诺基本上是两种方法的对象。一种方法是定义做什么,一个是告诉什么时候做。它必须是可以调用任何顺序,两种方法,所以对象需要跟踪其中一个被称为:

A promise is basically an object with two methods. One method is for defining what to do, and one is for telling when to do it. It has to be possible to call the two methods in any order, so the object needs to keep track of which one has been called:

var promise = {
  isDone: false,
  doneHandler: null,
  done: function(f) {
    if (this.isDone) {
        f();
    } else {
        this.doneHandler = f;
    }
  },
  callDone: function() {
    if (this.doneHandler != null) {
        this.doneHandler();
    } else {
        this.isDone = true;
    }
  }
};

您可以先定义的动作,然后触发它:

You can define the action first, then trigger it:

promise.done(function(){ alert('done'); });
promise.callDone();

您可以先触发动作,然后定义它:

You can trigger the action first, then define it:

promise.callDone();
promise.done(function(){ alert('done'); });

演示: http://jsfiddle.net/EvN9P/

当您在异步函数使用的承诺,该函数创建空的承诺,保持对它的引用,也返回引用。在code处理异步响应将触发该承诺的动作,和code调用异步函数定义操作。

When you use a promise in an asynchronous function, the function creates the empty promise, keeps a reference to it, and also returns the reference. The code that handles the asynchronous response will trigger the action in the promise, and the code calling the asynchronous function will define the action.

由于无论是那些可以以​​任意顺序发生,code调用异步函数可以挂在承诺和定义操作就是了任何时候。

As either of those can happen in any order, the code calling the asynchronous function can hang on to the promise and define the action any time it wants.

这篇关于如何承诺在JavaScript中工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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