[英]Node.js -> TypeError: Cannot read property 'then' of undefined at Context
I have a node.js file that is calling an async function and I keep getting a TypeError where property of "then" cannot be undefined at context.我有一个调用异步函数的 node.js 文件,并且我不断收到一个 TypeError ,其中“then”的属性不能在上下文中未定义。
async.js异步.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);
});
app/async应用程序/异步
exports = typeof window === 'undefined' ? global : window;
exports.asyncAnswers = {
async: function(value) {
},
manipulateRemoteData: function(url) {
}
};
Any help would be greatly appreciated!任何帮助将不胜感激!
Your async
function in app/async
needs to return a Promise object. app/async
async
函数需要返回一个 Promise 对象。 Right now, it isn't returning anything.现在,它没有返回任何东西。
You should change your async function in something like this using a Promise object:您应该使用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) {
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.