使用casperjs和每个文件上传多个文件

时间:2014-07-02 23:22:28

标签: casperjs

我正在尝试为其编写脚本的动态图像加载器。它需要逐个输入图像。

我尝试使用each添加导航步骤,但它不起作用(images来自之前的ajax调用,它是非空数组):

c.start(url)
.then(function fetchDetails(){
  fields = this.evaluate(function evalFetchDetails(){
    var response = __utils__.sendAJAX(fieldsUrl , 'GET', null, false);
    return JSON.parse( response );
  });
    images = [fields.z1, fields.z2, fields.z3, fields.z4, fields.z5, fields.z6, fields.z7, fields.z8];
})

我试过了:

.each(images, function uploadImage(self, img) {
    console.log("img:" + img); // this won't show
    c.page.uploadFile( '.upload-action [name=u]', img );
    c.waitWhileSelector(".loadingSmall", function(){
      console.log('loaded?'); // neither this
    }, null, 180000);
  })

那么有一种优雅的解决方法吗? 因为现在我已经陷入了这种嵌套 - 如果回调 - 便便,我的眼睛流血了:

.then( function uploadPhotos (){
    c.page.uploadFile('.upload-action [name=u]', fields['z1'])
    c.waitWhileSelector(".loadingSmall", function uploadImageAfterWhile(){
          console.log('loaded', fields.z1);
          if (fields.z2)
            c.page.uploadFile('.upload-action [name=u]', fields['z2'])
   ....

1 个答案:

答案 0 :(得分:1)

我想我应该在each中使用then

c.then(function uploadImages(){
    c.each(fields.images, function uploadImage(self, img) {
      c.then(function(){
        c.page.uploadFile( '.upload-action [name=u]', img );
        c.waitWhileSelector(".loadingSmall",
      });

否则(我怀疑)图片在运行c.each时不存在 - 但仅在之前的步骤之后,因此此处需要.then