Promise 在 JavaScript 中是如何工作的? [英] How do promises work in JavaScript?

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

问题描述

我刚刚实现了我的第一个函数,该函数根据 AngularJS 中的另一个承诺返回一个承诺,并且它起作用了.但在我决定只是这样做之前,我花了 2 个小时阅读并试图理解 Promise 背后的概念.我想如果我能写一段简单的代码来模拟 Promise 的工作原理,那么我就能从概念上理解它,而不是在不真正知道它是如何工作的情况下使用它.我不会写那个代码.

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 说明 Promise 是如何工作的吗?

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

推荐答案

promise 基本上是一个具有两种方法的对象.一种方法是定义做什么,一种方法是告诉什么时候做.必须可以以任意顺序调用这两个方法,因此对象需要跟踪调用了哪一个:

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/

在异步函数中使用promise时,该函数会创建空promise,保留对它的引用,并返回该引用.处理异步响应的代码会触发promise中的action,调用异步函数的代码会定义action.

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.

因为其中任何一个都可以以任何顺序发生,所以调用异步函数的代码可以挂在 promise 上并随时定义操作.

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.

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

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