您好,我正在进行两个 API 调用来进行一些检查,我想在两个调用完成后执行代码。
var firstCall = request.get('/first', function (error, response, body) {
body = JSON.parse(body)
})
var secondCall = request.get('/second', function (error, response, body) {
body = JSON.parse(body)
})
理想情况下,我想做这样的事情(例如使用下划线)
if (_.isEmpty(firstCall) && _.isEmpty(secondCall)) {
// execute code here because both calls are empty.
}
我相信我需要实现承诺,但我不确定如何为请求模块做到这一点。谢谢。
使用承诺:
(根据您共享的代码,我假设您使用的是旧版本的节点,因此我不会使用 ES6 语法)
var Promise = require('bluebird');
function get(url) {
return new Promise(function(resolve, reject) {
request.get(url, function(error, response, body) {
if (error) return reject(error);
resolve(JSON.parse(body));
});
});
}
var firstCall = get('/first');
var secondCall = get('/second');
Promise.all([firstCall, secondCall]).then(function (results) {
if(_.every(results, _.isEmpty)) {
// Do whatever you need to do
}
})
ES6版本:
const get = url => new Promise((resolve, reject) =>
request.get(url, (error, response, body) =>
error ? reject(error) : resolve(JSON.parse(body))
)
);
const firstCall = get('/first');
const secondCall = get('/second');
Promise.all([firstCall, secondCall]).then(results => {
if(_.every(results, _.isEmpty)) {
// Do whatever you need to do
}
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)