我有一个调用异步函数的node.js文件,我不断得到一个TypeError,其中“then”的属性不能在上下文中定义。
async.js
if ( typeof window === 'undefined' ) {
require('../../app/async');
var expect = require('chai').expect;
}
describe('async behavior', function() {
it('you should understand how to use promises to handle asynchronicity', function(done) {
var flag = false;
var finished = 0;
var total = 2;
function finish(_done) {
if (++finished === total) { _done(); }
}
// This is where the error occurs
asyncAnswers.async(true).then(function(result) {
flag = result;
expect(flag).to.eql(true);
finish(done);
});
asyncAnswers.async('success').then(function(result) {
flag = result;
expect(flag).to.eql('success');
finish(done);
});
expect(flag).to.eql(false);
});
应用/异步
exports = typeof window === 'undefined' ? global : window;
exports.asyncAnswers = {
async: function(value) {
},
manipulateRemoteData: function(url) {
}
};
非常感谢任何帮助!
答案 0 :(得分:1)
async
中的app/async
函数需要返回Promise对象。现在,它没有返回任何东西。
答案 1 :(得分:0)
您应该使用Promise对象以这种方式更改异步功能:
exports = typeof window === 'undefined' ? global : window;
exports.asyncAnswers = {
async: function(value) {
return new Promise(function (resolve, reject){
// DO YOUR STUFF HERE
// use resolve to complete the promise successfully
resolve(returnValueOrObject);
// use reject to complete the promise with an error
reject(errorGenerated);
});
},
manipulateRemoteData: function(url) {
}
};