简体   繁体   English

Promise 在 JavaScript 中是如何工作的?

[英]How do promises work in JavaScript?

I just implemented my first function that returns a promise based on another promise in AngularJS, and it worked.我刚刚实现了我的第一个函数,它根据 AngularJS 中的另一个承诺返回一个承诺,并且它起作用了。 But before I decided to just do it, I spent 2 hours reading and trying to understand the concepts behind promises.但在此之前,我决定它,我花了2小时来阅读,并试图了解背后的承诺的概念。 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.我想如果我能写一段简单的代码来模拟 Promise 是如何工作的,那么我就能从概念上理解它,而不是在不真正知道它是如何工作的情况下使用它。 I couldn't write that code.我写不出那个代码。

So, could someone please illustrate in vanilla JavaScript how promises work?那么,有人可以用普通的 JavaScript 来说明 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'); });

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

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中的action,调用异步函数的代码会定义action。

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.由于其中任何一个都可以以任何顺序发生,因此调用异步函数的代码可以挂在承诺上,并在需要时随时定义操作。

For the simplicity to understand about the promises in Javascript.为了简单理解 Javascript 中的承诺。 You can refer below example.你可以参考下面的例子。 Just copy paste in a new php/html file and run.只需复制粘贴到一个新的 php/html 文件中并运行。

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">

function test(n){
    alert('input:'+n);

    var promise = new Promise(function(fulfill, reject) {         
      /*put your condition here */
      if(n) {
        fulfill("Inside If! match found");
      }
      else {
        reject(Error("It broke"));
      }
    });
    promise.then(function(result) {
      alert(result); // "Inside If! match found"
    }, function(err) {
      alert(err); // Error: "It broke"
    });
}

</script>

</head>
<body>
<input type="button" onclick="test(1);" value="Test"/>

</body>
</html>
  1. Click on Test button,点击测试按钮,
  2. It will create new promise,它将创造新的承诺,
  3. if condition will be true it fulfill the response,如果条件为真,则满足响应,
  4. after that promise.then called and based on the fulfill it will print the result .在那个promise.then 之后调用并基于满足它会打印结果
  5. In case of reject promise.then returns the error message.如果拒绝promise.then返回错误消息。

Probably the simplest example of promises usage looks like that:可能最简单的 promise 使用示例如下所示:

var method1 = (addings = '') => {
  return new Promise(resolve => {
    console.log('method1' + addings)
    resolve(addings + '_adding1');
  });
}
var method2 = (addings = '') => {
  return new Promise(resolve => {
    console.log('method2' + addings)
    resolve(addings + '_adding2');
  });
}

method1().then(method2).then(method1).then(method2);
// result:
// method1            
// method2_adding1    
// method1_adding1_adding2
// method2_adding1_adding2_adding1

That's basic of basics.这是基础的基础。 Having it, you can experiment with rejects:有了它,您可以尝试拒绝:

var method1 = (addings = '*') => {
  return new Promise((resolve, reject) => {
    console.log('method1' + addings)
    resolve(addings + '_adding1');
  });
}
var method2 = (addings = '*') => {
  return new Promise((resolve, reject) => {
    console.log('method2' + addings)
    reject();
  });
}
var errorMethod = () => {
  console.log('errorMethod')
}
method1()
.then(method2, errorMethod)
.then(method1, errorMethod)
.then(method2, errorMethod)
.then(method1, errorMethod)
.then(method2, errorMethod);
// result:
// method1*           
// method2*_adding1
// errorMethod
// method2*
// errorMethod
// method2*

As we can see, in case of failure error function is fired (which is always the second argument of then ) and then next function in chain is fired with no given argument.正如我们所看到的,在失败的情况下,错误函数被触发(它总是then的第二个参数),然后链中的下一个函数在没有给定参数的情况下被触发。

For advanced knowledge I invite you here .对于高级知识,我邀请您来到这里

please check this simple promise code.请检查这个简单的承诺代码。 this will help you to better understand of promise functionality.这将帮助您更好地理解 Promise 功能。

A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it's not resolved.一个promise 是一个对象,它可能会在未来的某个时间产生一个单一的值:要么是一个已解决的值,要么是一个未解决的原因。 A promise may be in one of 3 possible states: fulfilled, rejected, or pending.承诺可能处于 3 种可能状态之一:已完成、拒绝或未决。 Promise users can attach callbacks to handle the fulfilled value or the reason for rejection. Promise 用户可以附加回调来处理已完成的值或拒绝的原因。

 let myPromise = new Promise((resolve, reject)=>{ if(2==2){ resolve("resolved") }else{ reject("rejected") } }); myPromise.then((message)=>{ document.write(`the promise is ${message}`) }).catch((message)=>{ document.write(`the promise is ${message}`) })

check this out看一下这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM