我有一个像这样的网址数组
var urls = ["www.google.com", "www.yahoo.com"];
我想循环遍历 url 并在循环内执行异步任务,并且在异步任务完成之前不会继续执行下一个项目。我知道你可以通过承诺做到这一点,但我在这方面遇到了一些麻烦。这是我有的
var xmlReader = require('cloud/xmlreader.js');
function readResponse_async(xlmString) {
var promise = new Parse.Promise();
xmlReader.read(xlmString, function (err, res) {
if(err) {
promise.reject(err);
} else {
promise.resolve(res);
}
});
return promise;
}
for (i = 0; i < urls.length; i++) {
Parse.Cloud.httpRequest({
url: unionUrls[i],
}).then(function(httpResponse) {
try {
// console.log(httpResponse.text)
return readResponse_async(httpResponse.text)
} catch (e) {console.log(e)}
}
但现在它不等待 readResponse_async 完成,我怎样才能让它等待呢?
Thanks
EDIT
阅读响应后,我将其保存到数据库中,并且我有另一个像这样的数组
var location = ['USA', 'England'];
我这样保存
function saveLoc_async(data, location) {
var i3, i4, i5, m,
TestItem = Parse.Object.extend("TestItem"),//can be reused within the loops?
promise = Parse.Promise.as();//resolved promise to start a long .then() chain
for (i3 = 0; i3 < data.count(); i3++) {
(function(testItem) {
testItem.set("item", data.at(i));
testItem.set("location", location);
//build the .then() chain
promise = promise.then(function() {
return testItem.save();
});
})(new TestItem());
//************************
//CALL retry(); here?
//**************************
}
因为有了你的回答我就有了
function retry() {
if (urlsUnion.length > 0) {
var nextUrl = urlsUnion.pop();
//********** ADDED LINE
var nextLoc = location.pop();
Parse.Cloud.httpRequest({
url: nextUrl,
}).then(function(httpResponse) {
xmlReader.read(httpResponse.text, function (err, res) {
if(err) {
// show an error
} else {
//********** ADDED LINE
saveLoc_async(res, nextLoc);
retry();
}
});
});
}
}
那么应该在哪里retry();
因为现在保存时有时会将第二个位置与第一个项目的 url 之一放在一起?为什么会发生这种情况?