手动封装
- 只需创建一个Promise对象,调用它的resolve()和reject()以及then()方法,then()里面也可以写箭头函数;
function verifyIdCard(idCardOptions) {
let options = {
// url: config.idCardKey.idCardHost + '?idCard=' + idCardOptions.idCard + '&name=' + idCardOptions.name,
url: 'https://idcert.market.alicloudapi.com/idcard',
method: 'GET',
qs: {
idCard: idCardOptions.idCard,
name: idCardOptions.name
},
headers: {
'cache-control': 'no-cache',
Authorization: 'APPCODE ' + config.idCardKey.idCardAppCode,
'Content-Type': 'application/json'
},
json: true
};
console.info(options)
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (!error && (response.statusCode === 200 || response.statusCode === 304)) {
let IdCardInfo = {
reqInfo: idCardOptions,
resInfo: body
}
console.info(IdCardInfo)
let idCardModel = new IdCardModel(IdCardInfo);
idCardModel.save();
resolve(body);
} else {
reject(error);
}
})
})
}
或者安装使用request-promise模块
npm install --save request
npm install --save request-promise
var rp = require('request-promise');
rp('http://www.google.com')
.then(function (htmlString) {
// Process html...
})
.catch(function (err) {
// Crawling failed...
});