[英]How to make JavaScript promise wait for another promise to be resolved inside for() loop
[英]JavaScript Promise - how to make multiple promise?
如何链接多重承诺? 例如:
var promise = new Promise(function(resolve, reject) {
// Compose the pull url.
var pullUrl = 'xxx';
// Use request library.
request(pullUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Resolve the result.
resolve(true);
} else {
reject(Error(false));
}
});
});
promise.then(function(result) {
// Stop here if it is false.
if (result !== false) {
// Compose the pull url.
var pullUrl = 'xxx';
// Use request library.
request(pullUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(body); // <-- I want to pass the result to the next promise.
} else {
reject(Error(false));
}
});
}
}, function(err) {
// handle error
});
promise.then(function(result) {
// Stop here if it is false.
if (result !== false) {
// handle success.
console.log(result);
}
}, function(err) {
// handle error.
});
错误:
解决(身体); ReferenceError:未定义解析
有任何想法吗?
链接Promises时,从then给出的函数返回的值应该是Promise或要传递的值。
在您的情况下,由于您要进行异步调用,因此只需返回另一个Promise,然后在其中进行呼叫reject
或resolve
。 如果不是异步的,则可以返回该值或引发错误,该错误还会传递给下一个then或错误处理程序/捕获。
另外,您需要将它们链接在一起,因为每个then()返回一个不同的Promise。
因此,如下所示:
var promise = new Promise(function(resolve, reject) {
// Compose the pull url.
var pullUrl = 'xxx';
// Use request library.
request(pullUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Resolve the result.
resolve(true);
} else {
reject(Error(false));
}
});
});
promise.then(function(result) {
// Stop here if it is false.
if (result !== false) {
var airportCode = result;
// Compose the pull url.
var pullUrl = 'xxx';
// Use request library.
return new Promise(function (resolve, reject) {
request(pullUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(body);
} else {
reject(Error(false));
}
});
});
}
}).then(function(result) {
// Stop here if it is false.
if (result !== false) {
// handle success.
console.log(result);
}
}).catch(function (err) {
// handle error
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.