使用承诺等待功能完成
Using promises to wait for function to finish
我已经在线阅读了一些有关 Promises 方法的教程,但我仍然有点困惑。
我有一个节点 app.js,它执行多种功能,包括连接到数据库。
db.connect(function(err) {
setupServer();
if(err) {
logger.raiseAlarmFatal(logger.alarmId.INIT,null,'An error occurred while connecting to db.', err);
return;
}
现在我写了一个mocha单元测试套件,它封装了这个应用程序并对其进行了多次请求调用。在某些情况下,测试会在未确认数据库已成功连接的情况下进行初始化,即:setupServer()
已执行。
如何为这段异步代码实现 promises 方法,如果不是 promises,我应该使用什么?我已经尝试过事件发射器,但这仍然不能满足所有要求并导致清理期间失败。
您需要在具有 async
功能的函数体内使用 Promise
。对于你的情况,我认为你说的 setupServer()
包含 ajax 个请求。
conts setupServer = () => {
return new Promise((resolve, reject) => {
//async work
//get requests and post requests
if (true)
resolve(result); //call this when you are sure all work including async has been successfully completed.
else
reject(error); //call this when there has been an error
});
}
setupServer().then(result => {
//...
//this will run when promise is resolved
}, error => {
//...
//this will run when promise is rejected
});
进一步阅读:
如果您使用的是 mocha,则应使用 asynchronous code approach。通过这种方式,您可以指示 mocha 等待您调用 done
函数,然后再继续其他操作。
这会让你开始:
describe('my test', function() {
before(function(done) {
db.connect(function(err) {
setupServer(done);
});
})
it('should do some testing', function() {
// This test is run AFTER 'before' function has finished
// i.e. after setupServer has called done function
});
});
假设您的 setupServer
在完成后调用 done
函数:
function setupServer(done) {
// do what I need to do
done();
}
我已经在线阅读了一些有关 Promises 方法的教程,但我仍然有点困惑。 我有一个节点 app.js,它执行多种功能,包括连接到数据库。
db.connect(function(err) {
setupServer();
if(err) {
logger.raiseAlarmFatal(logger.alarmId.INIT,null,'An error occurred while connecting to db.', err);
return;
}
现在我写了一个mocha单元测试套件,它封装了这个应用程序并对其进行了多次请求调用。在某些情况下,测试会在未确认数据库已成功连接的情况下进行初始化,即:setupServer()
已执行。
如何为这段异步代码实现 promises 方法,如果不是 promises,我应该使用什么?我已经尝试过事件发射器,但这仍然不能满足所有要求并导致清理期间失败。
您需要在具有 async
功能的函数体内使用 Promise
。对于你的情况,我认为你说的 setupServer()
包含 ajax 个请求。
conts setupServer = () => {
return new Promise((resolve, reject) => {
//async work
//get requests and post requests
if (true)
resolve(result); //call this when you are sure all work including async has been successfully completed.
else
reject(error); //call this when there has been an error
});
}
setupServer().then(result => {
//...
//this will run when promise is resolved
}, error => {
//...
//this will run when promise is rejected
});
进一步阅读:
如果您使用的是 mocha,则应使用 asynchronous code approach。通过这种方式,您可以指示 mocha 等待您调用 done
函数,然后再继续其他操作。
这会让你开始:
describe('my test', function() {
before(function(done) {
db.connect(function(err) {
setupServer(done);
});
})
it('should do some testing', function() {
// This test is run AFTER 'before' function has finished
// i.e. after setupServer has called done function
});
});
假设您的 setupServer
在完成后调用 done
函数:
function setupServer(done) {
// do what I need to do
done();
}