我想了解node.js中的承諾。這裏是一個示例代碼理解node.js中的承諾拒絕
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);
});
該代碼非常簡單。然而我有一個困惑。如果調用了return Promise.reject()
,函數會在哪裏調用哪個代碼。例如,如果第一個catch子句被調用,它調用返回Promise.reject()其中下面的代碼部分將隨後運行
承諾在for循環
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,
});
});
糾正我,如果我錯了,但應該只有一個'趕上()'鏈中的方法調用。如果你想在每一步之後支持捕獲錯誤,那麼你應該在'then()'方法中提供錯誤回調作爲第二個參數。 – sunpietro
注意:使用'.spread()'時,不要使用'.then(([rows,fields])=> {...})'而不是使用ES2015語法。 –
@MadaraUchiha爲什麼不鼓勵?性能? – thefourtheye