Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a promise

I know that't very silly, but how to start a promise chain? I have, for example,

var p = new Promise(function(resolve,reject) {
  setTimeout(function() {
    return resolve("Hi from promise after timeout");
  },1000);
});

How to run it? It should be like that,

when(p)
.then(function(msg) {
  console.log(msg);
})
.catch(function(error) {
  console.error(error);
});

But when is not defined.

like image 768
Kasheftin Avatar asked Jun 20 '16 16:06

Kasheftin


People also ask

What is an example of a promise?

as long as the sun rises at dawn each day. I promise to love you as long as you smile at me in your special way. I promise to give you some time on your own so to your own self be true. I promise to give you my help and support always, in all that you do.

How do promises execute?

Promises are basically javascript objects used asynchronously. In a synchronous execution, you don't need states, per se. Your code either successfully execute or fail to execute. In asynchronous code, we execute, wait for callbacks and decide if its success or failure and continue with the synchronous code execution.

What is a promise and how it works?

It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.


1 Answers

You just need to do:

p.then(function(msg) {
   console.log(msg);
})
.catch(function(error) {
  console.error(error);
});
like image 192
albertosh Avatar answered Sep 27 '22 16:09

albertosh