promise介绍
使用:
代码语言:javascript复制function getMessageData() {
var queryUrl = "http://1.1.1.1:1";
var param = {};
return new Promise((resolve, reject)=>{
request.post(queryUrl, JSON.stringify(param), function(result){
if(result.Result == 0 && result.Data.length > 0){
resolve(result.Data)
} else{
resolve('');
console.log('error', result);
}
}, function(error){
console.log(error);
reject('error', error);
})
}).catch((err)=>{
console.log('error', err);
})
}
涉及到关联多次查询的话,可以用链式操作
代码语言:javascript复制function getMessageData() {
var queryUrl = "http://1.1.1.1:1";
var param = {};
return new Promise((resolve, reject) => {
request.post(queryUrl, JSON.stringify(param ), function (result) {
if (result.Result == 0 && result.Data.length > 0) {
resolve(result.Data)
} else {
resolve('')
}
}, function (error) {
console.log(error)
reject(error)
})
}).then(data => {
var param = data;
return new Promise((resolve, reject) => {
request.post(queryUrl, JSON.stringify(param), function (result) {
if (result.Result == 0) {
resolve(result)
} else {
console.log(result)
resolve('')
}
}, function (error) {
console.log(error)
reject(error)
})
})
}).catch((err) => {
console.log(err)
})
}
调用:
代码语言:javascript复制async function loadData() {
var messageList = await getMessageData();
console.log(messageList );
}
还可以这样
代码语言:javascript复制function loadData(){
getMessageData().then(data => {
console.log(data);
});
}