node . js→TypeError: Cannot read property 'then'未定义的

Node.js -> TypeError: Cannot read property 'then' of undefined at Context

本文关键字:then 未定义 property read js TypeError Cannot node      更新时间:2023-09-26

我有一个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);
    });

app/异步

exports = typeof window === 'undefined' ? global : window;
exports.asyncAnswers = {
  async: function(value) {
 },
 manipulateRemoteData: function(url) {
 }
};

任何帮助都将非常感激!

app/async中的async函数需要返回一个Promise对象。现在,它没有返回任何东西

你应该像这样使用Promise对象来改变async函数:

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) {
  }
};