问题描述
我试图了解node.js中的promises。下面是一个示例代码
I am trying to understand promises in node.js. Here is a sample code
con.queryReturnPromise("SELECT * FROM bookings WHERE driverId = " + accId + " AND bookingStatus = " + config.get('BOOKING_STATUS_ACTIVE') + " LIMIT 1")
.catch((err) => {
callback({
"message": "Success",
"error": true,
});
console.log("mysql query error");
return Promise.reject();
})
.spread((rows, fields) => {
if (rows.length != 1) {
return Promise.reject();
}
mBooking = rows[0];
var query = "INSERT INTO locations SET timeStamp = " + timeStamp + " latitude = " + lat + ", longitude = " + lng + ", bookingId = " + mBooking.id;
return con.queryReturnPromise(query)
})
.catch((err) => {
if (err)
console.log("Adding Location error" + err);
return Promise.reject();
})
.spread(() => {
return funcs.getBooking(con, mBooking.id)
})
.then((booking) => {
if (mBooking.userId.toString() in userSockets) {
userSockets[mBooking.userId].emit(config.get('EVENT_USER_UPDATE_BOOKING'), {
"message": "Success",
"error": false,
"booking": booking
});
userId = mBooking.userId.toString();
}
callback({
"message": "Success",
"error": false,
"booking": booking
});
})
.catch((err) => {
if (err)
console.log(err);
});
代码非常简单。但是我有一个困惑。如果返回Promise.reject()
正在调用,函数将在哪里导致,将调用哪个代码。例如,如果第一个catch子句被调用并且它调用返回Promise.reject(),其中下面代码的一部分将在之后运行
The code is quite simple. However i have one confusion. If return Promise.reject()
is being called, where would the function lead to, Which code will be called. E.g if the first catch clause is called and it calls return Promise.reject() where part of below code will run afterwards
for循环中的Promise
Promises in for loop
data = JSON.parse(data);
var promisesArray = [];
for (var i = 0; i < data.length; i++)
{
var location = data[i];
var lng = location.lng;
var lat = location.lat;
var bearing = location.bearing;
var deltaTime = location.deltaTime;
var timeStamp = location.timeStamp;
var query = "INSERT INTO locations SET timeStamp = " + timeStamp + " latitude = " + lat + ", longitude = " + lng + ", bookingId = " + mBooking.id;
var promise = con.queryReturnPromise(query)
.then( () => {
});
promisesArray[] = promise;
}
Promise.all(promisesArray)
.then(function(results)
{
callback({
"error": false,
});
});
推荐答案
每次执行返回Promise.reject()
,该链中的下一个 .catch()
处理程序将被调用。它将跳过任何 .then()
处理程序,直到下一个 .catch()
处理程序。
Each time you do return Promise.reject()
, the next .catch()
handler in that chain will get called. It will skip any .then()
handlers up until the next .catch()
handler.
从 .then()
处理程序或 .catch()返回拒绝承诺
handler使当前的promise链被拒绝。因此,当遇到链中更多的处理程序时,链中的下一个拒绝处理程序将被调用。
Returning a reject promise from either a .then()
handler or a .catch()
handler makes the current promise chain be rejected. So, as more handlers down the chain are encountered, the next reject handler in the chain will get called.
当你点击 .catch时( )
处理程序,在 .catch()
之后会发生什么取决于 .catch()
没有。如果它抛出或返回被拒绝的promise,那么promise将保持在被拒绝状态,并且链中的下一个 .catch()
将被执行。如果它没有返回任何内容或任何常规值(除了最终拒绝的承诺),则承诺将被解析(不再被拒绝),然后下一个 .then()
处理程序链条运行。
When you hit a .catch()
handler, what happens after that .catch()
depends upon what the .catch()
does. If it throws or returns a rejected promise, then the promise stays in the rejected state and the next .catch()
in the chain will execute. If it returns nothing or any regular value (other than a promise that ultimately rejects), then the promise becomes resolved (no longer rejected) and then next .then()
handler in the chain runs.
以下是一个例子:
a().then(function() {
// makes promise chain assume rejected state
return Promise.reject();
}).then(function() {
// this will not get called because promise is in rejected state
}).catch(function() {
// this will get called
// returning a reject promise will keep the promise in the reject state
return Promise.reject();
}).then(function() {
// this will not get called because promise is in rejected state
}).catch(function() {
// this will get called
return 2;
}).then(function(val) {
// this will get called because prior `.catch()` "handled" the rejection
// already
console.log(val); // logs 2
}).catch(function() {
// this is not called because promise is in resolved state
});
这篇关于了解node.js中的promise拒绝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!