如何链接多重 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.
});
错误:
resolve(body); ReferenceError: resolve is not defined
有什么想法吗?
最佳答案
当链接 Promise 时,然后从给定 then 的函数返回的值应该是 Promise,或者要传递的值。
就您而言,由于您正在进行异步调用,因此您只需返回另一个 promise 并在其中调用 reject
或 resolve
即可。如果它不是异步的,您可以只返回值,或者抛出一个错误,该错误也会根据需要传递给下一个 then 或错误处理程序/catch。
此外,您需要将它们链接在一起,因为每个 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
});
这是一个具有工作版本的 JSFiddle:JSFiddle
关于JavaScript Promise - 如何做出多重 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40267215/