我想通過node.js中的JS Promises來工作,並且沒有獲得在不同函數之間傳遞promise的解決方案。JS承諾在函數之間傳遞/等待承諾
任務
對於主要的邏輯,我需要從一個REST API獲取的項目 JSON對象。 API處理本身位於api.js
文件中。
對API的請求通過request-promise模塊進行。我有一個私人的makeRequest
函數和公共幫助函數,如API.getItems()
。
index.js
中的主邏輯需要等待API函數,直到它可以執行。
問題
- 的承諾傳球樣的作品,但我不知道這是不是一個巧合。返回一個Promise返回
makeRequest
中的響應是否正確? - 我是否真的需要所有的承諾才能使主邏輯工作,只有等待項目設置後?有一種更簡單的方法嗎?
- 我仍然需要弄清楚,如何最好地處理a)
makeRequest
和b)getItems
函數的錯誤。對於承諾的最佳做法是什麼?傳遞錯誤對象?
這裏是我想出了現在的代碼: 起初我開始做與API請求:
// ./lib/api.js
var request = require('request-promise');
// constructor
var API = function() {
var api = this;
api.endpoint = "https://api.example.com/v1";
//...
};
API.prototype.getItems = function() {
var api = this;
var endpoint = '/items';
return new Promise(function (resolve, reject) {
var request = makeRequest(api, endpoint).then(function (response) {
if (200 === response.statusCode) {
resolve(response.body.items);
}
}, function (err) {
reject(false);
});
});
};
function makeRequest(api, endpoint) {
var url = api.endpoint + endpoint;
var options = {
method: 'GET',
uri: url,
body: {},
headers: {},
simple: false,
resolveWithFullResponse: true,
json: true
};
return request(options)
.then(function (response) {
console.log(response.body);
return response;
})
.catch(function (err) {
return Error(err);
});
}
module.exports = new API();
一些更多的背景
// index.js
var API = require('./lib/api');
var items;
function mainLogic() {
if (items instanceof Error) {
console.log("No items present. Stopping main logic.");
return;
}
// ... do something with items
}
API.getItems().then(function (response) {
if (response) {
console.log(response);
items = response;
mainLogic();
}
}, function (err) {
console.log(err);
});
api.js request模塊,與回調一起工作。由於這些被稱爲異步,項目從來沒有把它放在主邏輯上,我用Promise處理它。
在這裏,還有一個在'新的承諾'中包裝了現有的承諾[這是一種反模式](http://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-怎麼辦,我避免的,它)。你可以從'makeRequest'返回request(options)','getItems'返回makeRequest(api,endpoint)',最後看起來'mainLogic()'應該調用'getItems'而不是其他方法 – CodingIntrigue