我正在使用.then第一次,而不是。然後我使用回調函數。(node:2684)UnhandledPromiseRejectionWarning:未處理的承諾拒絕(拒絕ID:1):TypeError:無法讀取未定義的屬性'then'
下面是我的代碼片段:
phantom.create().then(function (ph) {
ph.createPage().then(function (page) {
page.open("http://codebeautify.org/xmlvalidator").then(function (status) {
page.render(base_pdf_path + lpnumber + '.pdf').then(function() {
console.log('PDF generated for waybill');
//Insert waybill url in db.
return waybill_url.insertWaybillUrl('Lpsimer', waybillUrl).then(function (waybill_inserted_resp) {
callback(null, true);
}).catch(function (error) {
callback(err_waybill_inserted);
});
});
});
});
});
上述功能調用的函數,而下面,這是在另一個文件,並呼籲正確的文件名是waybill.js:
var mongoose = require('mongoose');
var q = require('promised-io/promise');
var WaybillUrlSchema = new mongoose.Schema({
lpnumber: String,
url: String,
waybilltime: Date
});
module.exports = {
insertWaybillUrl: function (lpnumber, url) {
var defer = q.defer();
var waybill_insert = new waybill_url({
lpnumber: lpnumber,
url: url,
waybilltime: new Date()
});
//Save model to MongoDB
waybill_insert.save(function (err, inserted_waybill) {
if (err) {
return defer.reject(err);
}
else {
return defer.resolve(inserted_waybill);
}
});
}
};
以前我是用這個模式來做回調,它是工作的罰款:
waybill_url.insertWaybillUrl('Lpsimer', waybillUrl, function(err, success) {
if (err) {
} else {
}
)}
現在我公頃然後由於使用幻影代碼來編寫PDF而導致工作繁瑣。
需要關於如何在回調中進行回調的建議。
UPDATE
phantom.create().then(function (ph) {
ph.createPage().then(function (page) {
page.open("http://codebeautify.org/xmlvalidator").then(function (status) {
page.render(base_pdf_path + lpnumber + '.pdf').then(function() {
//Insert waybill url in db.
waybill_url.insertWaybillUrl('Lpsimer', waybillUrl).then(function (waybill_inserted_resp) {
if (waybill_inserted_resp) {
callback(null, true);
}
}).catch(function (error_waybill_url_insert) {
console.log("Error in inserting waybill:" + err_waybill_inserted);
callback(error_waybill_url_insert);
});
}).catch(function (error_render) {
console.log("error_render");
callback(error_render);
});
}).catch(function (error_open) {
callback(error_open);
});
}).catch(function (error_create_page) {
callback(error_create_page);
});
}).catch(function (error_phantom_create) {
callback(error_phantom_create);
});
現在我已經加入捕獲每一個然後由RSP在他的回答提出,但現在我得到我所獲取,並傳送到另一個回調錯誤:
Cannot read property 'then' of undefined
我得到這個錯誤,我添加了console.log(「error_render」); 那就是我在調用幻像的page.render函數的地方。
我的要求很簡單。我想用phantom生成一個PDF文件,然後我只想調用另一個函數,它位於另一個文件waybill_url,函數名稱:waybill_url.insertWaybillUrl。但由於回調和異步行爲,這兩個函數的簡單調用越來越麻煩。
我已經做了更新。請幫助我進一步移動,因爲現在我在捕獲中發生錯誤,無法再調用undefined。我知道這個錯誤很常見,並且在互聯網上有很多解決方案,但我無法解決。任何幫助將不勝感激。謝謝。 – Simer
@Simer你能解決這個問題嗎?我很好奇你是如何修復它的。謝謝 – Oliver
@oliver我只是將返回waybill_url.insertWaybillUrl轉移到另一個函數,以便我不必在.then之後調用任何其他函數。這解決了我暫時的問題。因此,在「console.log('爲運單提供生成的PDF');」我只寫回調(null,true)。 對不起,但沒有找到任何明確的解決方案,這個錯誤,我也沒有找到它的原因。 – Simer