我想在下面的測驗中添加對同步函式的呼叫:
describe('the server', function() {
it('should respond to a udp packet', function(done) {
// TODO: call async function here
const udp = dgram.createSocket('udp4');
udp.on('error', function(error) {
console.log(error);
});
udp.on('message', function(msg, rinfo) {
console.log('msg', msg);
console.log('rinfo', rinfo);
// TODO: check the reply
udp.close();
done();
});
udp.bind();
// send a request
const bytes = Buffer.from("421a0800117860bc457f0100001a0653455256455222054d54303031", 'hex');
udp.send(bytes, SERVER_PORT, SERVER_ADDR)
});
});
如果我只是添加async, 來制作:
it('should respond to a udp packet', async function(done) {
我收到一個錯誤:
1) the server
should respond to a udp packet:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
但我需要,done因為只有從服務器接收到資料包時測驗才結束。
有沒有一種方法只能從內部函式中的異步函式“回傳”?
uj5u.com熱心網友回復:
這里至少有兩種方法:使用異步呼叫回傳的承諾或使整個測驗函式異步。我將展示第二種方法,因為它更容易實作,而無需知道 todo 中的異步函式呼叫是什么樣的。
基本上要進行三個更改:
- 使測驗函式異步并洗掉
done引數。 done將使用回呼的陳述句或陳述句組包裝在Promise 中。done如果要保留該名稱,請命名Promise 回呼的第一個引數。- 回報承諾。
describe('the server', function() {
it('should respond to a udp packet', async function() {
// TODO: call async function here
const udp = dgram.createSocket('udp4');
udp.on('error', function(error) {
console.log(error);
});
const promise = new Promise(done => {
udp.on('message', function(msg, rinfo) {
console.log('msg', msg);
console.log('rinfo', rinfo);
// TODO: check the reply
udp.close();
done();
});
});
udp.bind();
// send a request
const bytes = Buffer.from("421a0800117860bc457f0100001a0653455256455222054d54303031", 'hex');
udp.send(bytes, SERVER_PORT, SERVER_ADDR);
return promise;
});
});
這應該足以進行測驗。為了更準確的錯誤處理,您可能希望在出現例外時拒絕承諾:
const promise = new Promise((done, reject) => {
try {
udp.on('message', function(msg, rinfo) {
console.log('msg', msg);
console.log('rinfo', rinfo);
// TODO: check the reply
udp.close();
} catch (err) {
reject(err);
return;
}
done();
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436150.html
