How to call a function with a promise

promise javascript
javascript promise then
promise then return value
promise chaining
javascript promise w3schools
return a promise from a function
promise catch
then is not a function

I'm fairly new to JS and I'm trying to understand the documentation in a npm package. The documentation is:

client.projects.get(); // Promise

I've read some documentation on Promises, but I'm still not sure how to call this and get it to return what I am expecting.

For reference the package is here: https://github.com/markmssd/bitbucket-server-nodejs

A Promise is async execution of the code.

You can get the value returned from that async code using .then method on a Promise. You will have to pass the callback function which handles the value returned.

client.projects.get().then(function(foo) {
// this foo is returned from client.projects.get() async operation
})

In case that async operation threw some Exception, you can catch those using a .catch on a promise.

client.projects.get().then(function(foo) {
    // this foo is returned from client.projects.get() async operation
}).catch(function(err) {
   // something went wrong while executing client.projects.get()
})

Using Promises to call function inside another function with Bluebird , All further calls of resolve and reject are ignored: let promise = new Promise ( function ( resolve , reject ) { resolve ( "done" ) ; reject ( new Error  This second promise (promise2) represents the completion not just of doSomething(), but also of the successCallback or failureCallback you passed in, which can be other asynchronous functions returning a promise.

client.projects.get(); will return a promise and not probably "what you are expecting".

What you should do is to call it like this:

client.projects.get().then((result) => {
    // do with `result` your logic
    console.log(result);
});

and then inside the callback passed as argument to the then function receive the result the response provides and use it according to your logic.

Promise, As you shown above, you can use the resolve function to fullfil the promise. The then function binds a callback to the promise and you can use the data given to the resolve function. The reject function is used to trigger an error. When you use then , you can give 2 functions. This wrapper allows us to call the getChuckNorrisFact function like a promise with the .then () and .catch () methods. When the getChuckNorrisFact is called, it executes the request to the API and waits for either a resolve () or a reject () statement to execute.

Play around with:

client.projects.get().then(result => console.log(result))

You will notice when working with a promise that you will need to specify what to do with its result once it is ready.

An alternative where you are simply returning the result would be:

client.projects.get().then(res => res)

If there is an error, you'll also want to add a catch:

client.projects.get().then(res => res).catch(err => console.error(err))

This will log out an error if there is a failure or some sort.

Your first code with promises, constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject. var createProjectFolder = function (projectName) { normalizeFilePath(projectName) .then(checkFileExistance) .then(function (exists) { if (!exists) { // create folder } }) .catch(function (error) { // if there are any errors in promise chain // we can catch them in one place, yay!

A Promise object represents a value that may not be available yet but will be resolved at some point in the future. It allows you to write asynchronous code in a more synchronous fashion. You can get the result once the promise resolved or catch the error in case of promise reject(failure). In your case, you have to call the function like this:

  client.projects.get().then(function(result){
       console.log(result);
    }).catch(function(err) {
        // handle error
        console.log("something went wrong",err);
     });

Alternatively, You can also store promise into variable returned from the function call and get the result, like this:

var promise = client.projects.get();

promise.then(function(result){
   console.log(result);
}).catch(function(err) {
    // handle error
    console.log("something went wrong",err);
 });

Having assigned promises into a variable may not be a good choice but It is very useful when there is more than one function which returns a promise and we want to execute some code after all promises have resolved. Something like this:

var p1 = asyncFunction1();
var p2 = asyncFunction2();
Promise.all([p1,p2]).then(function(results){
 // do something with results
});

You can also check this nice blog on promises

Converting callbacks to promises, . To learn about the way promises work and how you can use them, we advise you to read Using promises first. Many functions may need that result. These are the “fans”. A promise is a special JavaScript object that links the “producing code” and the “consuming code” together. In terms of our analogy: this is the “subscription list”. The “producing code” takes whatever time it needs to produce the promised result,

> p.then(onFulfilled[, onRejected]);

onFulfilled - A Function called if the Promise is fulfilled.

onRejected (Optional) - A Function called if the Promise is rejected.

p.then(function(value) {
   // fulfillment
 }, function(reason) {
  // rejection
 });
> try -> catch -> finally
p.then(function(data) { console.log("Play with your data.") })
   .catch(function(error) { console.log(error); })
   .finally(function() { console.log("Something need to do, no matters fail or sucess") });
  1. The finally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.
  2. The finally() method is very similar to calling .then(onFinally, onFinally)

For more details.


So, you can write your code like:

 client.projects.get().then(function(value) {
    // fulfillment
  }, function(reason) {
    // rejection
  });

Or

 client.projects.get()
   .then(function(data) { console.log("Play with your data.") })
   .catch(function(error) { console.log(error); })
   .finally(function() { console.log("Finally do something.") });

Getting to know asynchronous JavaScript: Callbacks, Promises and , Callback Hell. Callbacks are a useful feature of JavaScript's that enables it make asynchronous calls. They are functions that are usually passed  If the operation is successful, pass that data to the code that uses that promise, otherwise pass error The code which uses a promise should call then function on that promise. It takes two

JavaScript Promises: an Introduction, You wrap the whole function in a Promise, and instead of calling the callback, you call resolve (or reject if there is an error). The function returns this Promise object. This is called a Promise Chain. Calling APIs, downloading files, reading files are among some of the usual async operations that you'll perform. World Before Promises: Callback. Must we use promise for asynchronous call? Nope. Prior to Promise, we use callback. Callback is just a function you call when you get the return result. Let's modify the previous example to accept a callback.

Promise, var promise = new Promise(function(resolve, reject) { Do something within the callback, perhaps async, then call resolve if everything worked  The example function tetheredGetNumber() shows that a promise generator will utilize reject() while setting up an asynchronous call, or within the call-back, or both. The function promiseGetWord() illustrates how an API function might generate and return a promise in a self contained manner.

How to make a Promise out of a Callback function in JavaScript, function asyncFunc () { return new Promise ( function ( resolve , reject ) { ··· resolve then() always returns a Promise, which enables you to chain method calls:. The async function will still return a promise object if called without an await (or in non asynchronous code). Check the result of console.log (waitForPromise ()) if you are uncertain. A check of console.log (result) within the async function will print out what you expect, but the return from the async function happens immediately without

Comments
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • you clearly haven't read about promises then.
  • Please add what you have tried. You have a Promise that you have gotten back from .get(). what have you tried to do with it? What did the documentation that you read say to do with it? What didn't work? What do you think went wrong. Your question is too broad right now.
  • Thank you - this makes sense, I was just having issues with the syntax even after reading docs on this.
  • what kind of issue are you having with the syntax ?