如何使用承诺调用函数 [英] How to call a function with a promise
问题描述
我对 JS 还很陌生,我正在尝试理解 npm 包中的文档.文档是:
I'm fairly new to JS and I'm trying to understand the documentation in a npm package. The documentation is:
client.projects.get();//承诺
我已经阅读了一些关于 Promises 的文档,但我仍然不确定如何调用它并让它返回我所期望的.
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.
参考包在这里:https://github.com/markmssd/bitbucket-server-nodejs
推荐答案
Promise
是代码的异步执行.
您可以使用 Promise 上的 .then
方法获取从异步代码返回的值.您必须传递处理返回值的回调函数.
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
})
如果异步操作抛出了一些异常,您可以在承诺上使用 .catch
捕获那些异常.
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()
})
这篇关于如何使用承诺调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!