我正在嘗試用玩笑和承諾進行測驗。
當我嘗試在控制臺中寫入時,結果從我有一個未定義值的承諾中得到
這是我的測驗代碼:
describe("Search concurrent with promises", () => {
describe("Test 10: Several searches in DDBB", () => {
function connection(){
let ddbb = new PGMappingDDBB();
return new Promise((resolve, reject) => {
let db = ddbb.connect();
//resolve("Hello World");
resolve(db);
});
}
test("Test 12: Several searches concurrently", () => {
connection().then(ddbb => {
console.log(ddbb);
});
});
});
});
ddbb.connect()是一個異步函式。connect() 的代碼是:
async connect(){
this.client = await poolMapping.connect();
}
當我嘗試撰寫ddbb未定義的變數狀態時。
但是,如果我評論resolve(db)并洗掉 的評論resolve("Hello World"),當我寫下ddbbIve got的值時"Hello World"。
我究竟做錯了什么?
編輯我:
ddbb.connect() 回傳一個 Promise。如果我寫什么回傳console.log(ddbb.connect())。我有:
Promise { <pending> }
uj5u.com熱心網友回復:
解釋:
async connect(){
this.client = await poolMapping.connect();
// NOTE: There is no return value
}
describe("Search concurrent with promises", () => {
describe("Test 10: Several searches in DDBB", () => {
function connection(){
let ddbb = new PGMappingDDBB();
return new Promise((resolve, reject) => {
let db = ddbb.connect();
// ^^ this will be undefined, as connect has no return value
resolve(db);
// ^^^^^^^^^^^^ Resolving the promise with undefined
});
}
test("Test 12: Several searches concurrently", () => {
connection().then(ddbb => {
console.log(ddbb);
/// ^^^^ will be undefined
});
});
});
});
此外,jest 不會等待 promise 的結果,并且您不會在測驗中斷言任何內容,因此它總是會成功。
在處理 Promise 時,如果你從測驗中回傳 Promise,Jest 會等待它。但是您仍然需要斷言該值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/485360.html
標籤:javascript 承诺 开玩笑的
