[英]How to call a function with a promise
我是JS的新手,我想了解npm軟件包中的文檔。 該文檔是:
client.projects.get(); // Promise
我已經閱讀了有關Promises的一些文檔,但是我仍然不確定如何調用它並使它返回我期望的結果。
作為參考,該軟件包在這里: https : //github.com/markmssd/bitbucket-server-nodejs
Promise
是代碼的異步執行。
您可以在Promise上使用.then
方法獲取該異步代碼返回的值。 您將必須傳遞處理返回值的回調函數。
client.projects.get().then(function(foo) {
// this foo is returned from client.projects.get() async operation
})
萬一異步操作拋出異常,您可以在諾言中使用.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().then(result => console.log(result))
您會注意到,在兌現承諾時,一旦准備好,您將需要指定如何處理其結果。
僅返回結果的替代方法是:
client.projects.get().then(res => res)
如果有錯誤,您還想添加一個catch:
client.projects.get().then(res => res).catch(err => console.error(err))
如果出現故障或某種原因,這將注銷錯誤。
Promise對象表示一個值,該值可能尚不可用,但將來會被解析。 它允許您以更同步的方式編寫異步代碼。 一旦承諾解決,您就可以得到結果,或者在承諾被拒絕(失敗)的情況下捕獲錯誤。 在您的情況下,您必須像這樣調用該函數:
client.projects.get().then(function(result){
console.log(result);
}).catch(function(err) {
// handle error
console.log("something went wrong",err);
});
另外,您還可以將promise存儲到從函數調用返回的變量中並獲取結果,如下所示:
var promise = client.projects.get();
promise.then(function(result){
console.log(result);
}).catch(function(err) {
// handle error
console.log("something went wrong",err);
});
將promise分配給變量可能不是一個好選擇,但是當有多個函數返回promise並且我們希望在所有promise都解決后執行一些代碼時,這將非常有用。 像這樣:
var p1 = asyncFunction1();
var p2 = asyncFunction2();
Promise.all([p1,p2]).then(function(results){
// do something with results
});
onFulfilled-如果實現承諾,則調用此函數。
onRejected (可選)-如果Promise被拒絕,則調用此函數。
p.then(function(value) { // fulfillment }, function(reason) { // rejection });
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") });
有關更多詳細信息 。
因此,您可以像下面這樣編寫代碼:
client.projects.get().then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
要么
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.