[英]JavaScript Promise - how to make multiple promise?
How can I chain the multiple promise? 如何链接多重承诺? For instance:
例如:
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.
});
Error: 错误:
resolve(body);
解决(身体); ReferenceError: resolve is not defined
ReferenceError:未定义解析
Any ideas? 有任何想法吗?
When chaining Promises, then return value from a function given to then should either be a Promise, or the value to pass along. 链接Promises时,从then给出的函数返回的值应该是Promise或要传递的值。
In your case, since you're making an async call, you'll just return another promise and call reject
or resolve
within there. 在您的情况下,由于您要进行异步调用,因此只需返回另一个Promise,然后在其中进行呼叫
reject
或resolve
。 If it wasn't async, you could just return the value, or throw an error, which also gets passed along to the next then or error handler/catch as appropriate. 如果不是异步的,则可以返回该值或引发错误,该错误还会传递给下一个then或错误处理程序/捕获。
Also, you need to chain them together, because each then() returns a different Promise. 另外,您需要将它们链接在一起,因为每个then()返回一个不同的Promise。
So, something like this: 因此,如下所示:
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
});
Here is a JSFiddle with a working version: JSFiddle 这是带有工作版本的JSFiddle : JSFiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.