admin管理员组

文章数量:1279053

I've dealt with JavaScript years ago. So I'm familiar with the term "event" as an function which is automatically executed when a certain event happens. Please correct me in case my definition is wrong.

Now I have to deal with the language again. Try to get an idea from this promise-thing which is new to me. But can't find any good definition for it.

Can anyone give an easy to understand definition of what JavaScript promises are?

More over: They seem to me very similar to events. You define a callback-function which is automatically called when a certain event happens.

What's the difference between JavaScript-events and -promises?

I've dealt with JavaScript years ago. So I'm familiar with the term "event" as an function which is automatically executed when a certain event happens. Please correct me in case my definition is wrong.

Now I have to deal with the language again. Try to get an idea from this promise-thing which is new to me. But can't find any good definition for it.

Can anyone give an easy to understand definition of what JavaScript promises are?

More over: They seem to me very similar to events. You define a callback-function which is automatically called when a certain event happens.

What's the difference between JavaScript-events and -promises?

Share Improve this question asked May 6, 2016 at 10:56 ts248ts248 3612 gold badges5 silver badges11 bronze badges 8
  • 2 Did you search anything ? Google gave me about 69,000 results – Rayon Commented May 6, 2016 at 11:00
  • MDN seems to define it pretty well: developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – David Commented May 6, 2016 at 11:01
  • 1 Promises are used for deferred and asyncronous putations / operations and represents operations that hasn't pleted yet and can actually assume different states (pending, fulfilled and rejected) (or, really, pending -> waiting, fullfilled -> success, rejected -> errror). Events are instead interfaces that represents an event fired by the dom, so they technically are properties offered by the DOM, I can't really foresee many conceptual relations between promises and events to be entirely honest. – briosheje Commented May 6, 2016 at 11:02
  • @Rayon So then: What's the difference to an event? – ts248 Commented May 6, 2016 at 11:02
  • 1 @ts248, How could you relate among Promise and Events ? I'm not sure what you are asking.. :( – Rayon Commented May 6, 2016 at 11:03
 |  Show 3 more ments

2 Answers 2

Reset to default 9

For the first view, they are very similar. In events, you have a callback function, and in Promise you have a callback-function. Even more, technically, you can do almost similar stuff which Promises do only with Events.

Events and Promises both useful for Async code. I will write some abstract code to try explain. For example, you have some async code, and after that, it should alert something.

function someAsyncFunction() {
    setTimeout(function() {
        // some long async logic here
        console.log('What the hell is Promises?');
    }, 2000);
}
someAsyncFunction();

Timeout here is Async, because it will run your code not in main tread and run it after some time, you not sure when exactly it happens (ofcouse here it's around 2s. less-or-more).

So now imagine, that you need to do something with result of async action. For example you have function AsyncResultCalculator and you need to run that function. What you will do? You have few choices:

  • Pass a callback function to async code and run your function AsyncResultCalculator when async code plete it's work
  • Define some Event (for example 'DoSomethingAfterAsync' event) and trigger that event after async code is finished or failed.
  • Use promises

All this variants as result, will do only one thing - run your function AsyncResultCalculator. So, why we have 3 different ways to do the same result? Because it's cool! It's just different techniques to do the same stuff, but they change difficulty of your code. Some ways make your code more plicated, some ways make your code larger, some ways make your code more elegant.

So, i think you know how to run callback functions or how to trigger event, but what about Promises? How to use them? Very easy. Let's go back to Async Timeout and look:

function AsyncResultCalculator(res) {
    // calculate result of async action!!!
    console.log(res + 1);
}

function someAsyncFunction() {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            // some long async logic here
            resolve(55); // or reject
        }, 2000);
    }
}

someAsyncFunction().then(AsyncResultCalculator);

So, what the point to use Promises here? Just because it's modern style for async actions. With promises your code will be more elegant and more easy to read for different developers. Also, promises is useful because you can build a CHAIN of function like

someAsyncFunction()
    .then(function(){ ... })
    .then(function(){ ... });

But, of course, in some cases, it's not bad to use callbacks or events. For example, events is more useful, if you need to catch async result in some different JS file and you don't want to uses promises or callbacks in original file with async action.

All JavaScript language is mix of events, callbacks and promises ;D Use it with wise.

  • Use events for DOM events or some plicated situations.
  • Use promises for async actions
  • Use callbacks for sync actions or where you don't want to use Promises

At their most basic, promises are a bit like event listeners except:

  • A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.
  • If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.

Check out this JavaScript Promises: an Introduction

本文标签: Definition of a JavaScript promise and what is the difference to an eventStack Overflow