我在使用promises编写异步函数时遇到了麻烦
function requestsPlot(plot, info) {
return new Promise(function(resolve, reject) {
var plotObject = fieldsObject[plot]
var sqr = new Promise(function(resolve1, reject) {
debugger;
get(createSQRurl(plotObject.polygon))
.then(function(result) {
plotObject.quality = sqrHtmlParsing(result);
resolve1();
});
});
var soilType = new Promise(function(resolve2, reject) {
get(createSoilTypeUrl(plotObject.polygon))
.then(function(result) {
plotObject.soilType = soilTypeHtmlParsing(result);
resolve2();
});
});
var distance = new Promise(function(resolve3, reject) {
var start = turf.centerOfMass(plotObject.polygon).geometry.coordinates;
var end = info.homeCoords;
get('http://router.project-osrm.org/route/v1/driving/' + start + ';' + end + '?overview=false')
.then(function(result) {
var parsed = JSON.parse(result);
if (parsed.code == 'Ok') {
plotObject.distance = parsed.routes[0].distance / 1000;
resolve3()
} else {
plotObject.distance = '';
resolve3()
}
});
});
Promise.all([sqr, soilType, distance]).then(function() {
resolve('test');
})
})
}
在解决函数内部的所有promise(变量sqr,soilType和distance)之后,想法是解决requestPlot函数返回的promise。但是,当get函数中的所有请求仍处于挂起状态时,将解除promise。请注意,' get'函数也返回一个promise。 非常感谢你的帮助!
P.S。这里是获取功能
function get(url) {
var requestPromise = new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('get', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
}
else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
return requestPromise
}
答案 0 :(得分:8)