简体   繁体   English

如何以承诺方式调用函数

[英]How to call a function with a promise

I'm fairly new to JS and I'm trying to understand the documentation in a npm package. 我是JS的新手,我想了解npm软件包中的文档。 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. 我已经阅读了有关Promises的一些文档,但是我仍然不确定如何调用它并使它返回我期望的结果。

For reference the package is here: https://github.com/markmssd/bitbucket-server-nodejs 作为参考,该软件包在这里: https : //github.com/markmssd/bitbucket-server-nodejs

A Promise is async execution of the code. Promise是代码的异步执行。

You can get the value returned from that async code using .then method on a Promise. 您可以在Promise上使用.then方法获取该异步代码返回的值。 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. 万一异步操作抛出异常,您可以在诺言中使用.catch捕获那些异常。

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()
})

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. 然后在作为参数传递给then函数的回调内部,接收响应提供的result ,并根据您的逻辑使用它。

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: 如果有错误,您还想添加一个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. 如果出现故障或某种原因,这将注销错误。

A Promise object represents a value that may not be available yet but will be resolved at some point in the future. Promise对象表示一个值,该值可能尚不可用,但将来会被解析。 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: 另外,您还可以将promise存储到从函数调用返回的变量中并获取结果,如下所示:

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. 将promise分配给变量可能不是一个好选择,但是当有多个函数返回promise并且我们希望在所有promise都解决后执行一些代码时,这将非常有用。 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 您也可以查看关于诺言的这个不错的博客

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

onFulfilled - A Function called if the Promise is fulfilled. onFulfilled-如果实现承诺,则调用此函数。

onRejected (Optional) - A Function called if the Promise is rejected. onRejected (可选)-如果Promise被拒绝,则调用此函数。

 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. 如果您希望在兑现承诺后进行一些处理或清理,而不管其结果如何,那么finally()方法将很有用。
  2. The finally() method is very similar to calling .then(onFinally, onFinally) finally()方法与调用.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.") });

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

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