Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 请求承诺+;量角器测试中的co-API触发器_Javascript_Protractor_Generator_Require - Fatal编程技术网

Javascript 请求承诺+;量角器测试中的co-API触发器

Javascript 请求承诺+;量角器测试中的co-API触发器,javascript,protractor,generator,require,Javascript,Protractor,Generator,Require,我想从量角器测试调用module.api.create。参考此解决方案:- 我使用的是request promise+co,如下所示:- //api/module1.js var co = require('co'); var rp = require('request-promise'); exports.create = co(function* def() { var response, token; urlLogin.body.username = username;

我想从量角器测试调用module.api.create。参考此解决方案:- 我使用的是request promise+co,如下所示:-

//api/module1.js
var co = require('co');
var rp = require('request-promise');

exports.create =  co(function* def() {
    var response, token;
    urlLogin.body.username = username;
    response = yield rp(urlLogin);
    //extract token and run other APIs
    ...
}).catch(err => console.log);

在我的规范/测试中,我添加了

api = require('../../api/api');
api.module1.create;  
我面临的问题是,即使不调用“api.module1.create;”行,require行“api=require(“../../api/api”);“也会在每次从
co执行测试时自动调用create:

co@4.0.0已经发布,现在依赖于承诺。这是迈向异步/等待方案的垫脚石。主要的API更改是如何调用co()。之前,co返回了一个“thunk”,然后用回调和可选参数调用它。现在,co()返回一个承诺

我相信您正在寻找
co.wrap
,它返回一个函数,该函数执行生成器并返回承诺(该函数也可以称为thunk)。使用just
co
急切地执行生成器并返回执行生成器的结果

const co = require('co')

co(function* () {
  // this will run
  console.log('hello from plain co!')
})

co.wrap(function* () {
  // this won't run because we never call the returned function
  console.log('hello from wrapped co 1!')
})

const wrappedfn = co.wrap(function* () {
  // this runs because we call the returned function
  console.log('hello from wrapped co 2!')
})

wrappedfn()  
您还可以自己包装一个函数,它的作用与
co.wrap
相同,并允许您在以后做更多的事情

exports.create = function() {
  return co(function* () {
    // this will run only when exports.create is called
    console.log('hello from plain co!')
  })
  // If you want to do stuff after and outside the generator but inside the enclosing function
  .then(...)
}

呃,您想使用
co.wrap
来创建函数,而不是
co
来评估承诺?
exports.create = function() {
  return co(function* () {
    // this will run only when exports.create is called
    console.log('hello from plain co!')
  })
  // If you want to do stuff after and outside the generator but inside the enclosing function
  .then(...)
}