GVKun编程网logo

javascript – 有没有正确的方法来存储已解决的承诺?(js的存储方式)

15

本文将分享javascript–有没有正确的方法来存储已解决的承诺?的详细内容,并且还将对js的存储方式进行详尽解释,此外,我们还将为大家带来关于javascript–Jcrop没有正确裁剪图像、ja

本文将分享javascript – 有没有正确的方法来存储已解决的承诺?的详细内容,并且还将对js的存储方式进行详尽解释,此外,我们还将为大家带来关于javascript – Jcrop没有正确裁剪图像、javascript – mobx商店中的承诺、javascript – Typescript:等待所有的承诺、javascript – 为什么.json()会返回一个承诺?的相关知识,希望对你有所帮助。

本文目录一览:

javascript – 有没有正确的方法来存储已解决的承诺?(js的存储方式)

javascript – 有没有正确的方法来存储已解决的承诺?(js的存储方式)

现在几乎每个节点包都有回调api.如果我正在编写包装器,例如ORM,该怎么办?

const Promise = require('bluebird');
const mongo = Promise.promisifyAll(require('mongodb'));

class ORM {
  constructor(mongoUrl) {
    this.db = mongo.connectAsync(mongoUrl);
  }

  collection(name) {
    return this.db.then((db) => {
      return db.collectionAsync(name);
    });
  }
}

这是对的吗?

解决方法

好吧,承诺只是代表价值时间的代理.

你正在做的事情非常好.存储承诺是可以的,事实上,存储承诺通常更好,而不是存储它们的值,因为这样可以减少竞争条件.

你正在做的唯一问题是错误处理.假设连接失败了 – 在实际向数据库发出请求之前,您没有对它做出反应或检测它,这并没有太大意义.您应该决定如何在构造函数中处理连接失败并处理它.

如果您想明确禁止检测到未处理的拒绝,您可以执行以下操作:

this.db = mongo.connectAsync(mongoUrl);
this.db.catch(() => {});

虽然我个人建议不要使用它,但您应该重新连接逻辑,如果多次重新连接尝试失败,甚至可能会使服务器崩溃.

javascript – Jcrop没有正确裁剪图像

javascript – Jcrop没有正确裁剪图像

我的jcrop代码
$(function(){

// Create variables (in this scope) to hold the API and image size
var jcrop_api,boundx,boundy,// Grab some information about the preview pane
    $preview = $('#preview-pane'),$pcnt = $('#preview-pane .preview-container'),$pimg = $('#preview-pane .preview-container img'),xsize = $pcnt.width(),ysize = $pcnt.height();

//console.log('init',[xsize,ysize]);
$('#target').Jcrop({
  onChange: updateInfo,onSelect: updateInfo,onRelease: clearInfo,setSelect: [0,150,180],BoxWidth: 400,BoxHeight: 300,allowMove: true,allowResize: true,allowSelect: true,aspectRatio: xsize / ysize
},function(){
  // Use the API to get the real image size
  var bounds = this.getBounds();
  boundx = bounds[0];
  boundy = bounds[1];
  // Store the API in the jcrop_api variable
  jcrop_api = this;

  // Move the preview into the jcrop container for css positioning
  $preview.appendTo(jcrop_api.ui.holder);
});


   // update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
    if (parseInt(e.w) > 0) {
        var rx = xsize / e.w;
        var ry = ysize / e.h;

        $pimg.css({
            width : Math.round(rx * boundx) + 'px',height : Math.round(ry * boundy) + 'px',marginLeft : '-' + Math.round(rx * e.x) + 'px',marginTop : '-' + Math.round(ry * e.y) + 'px'
        });
    }
    $('#x1').val(e.x);
    $('#y1').val(e.y);
    $('#w').val(e.w);
    $('#h').val(e.h);
};

// clear info by cropping (onRelease event handler)
function clearInfo() {
    $('#w').val('');
    $('#h').val('');
};


   });

   Java controller which handles it

@RequestMapping(value = "/editProfileImage",method = RequestMethod.POST)
public @ResponseBody
FileMeta edit(MultipartHttpServletRequest request,@RequestParam(value = "x1") final int x1,@RequestParam(value = "y1") final int y1,@RequestParam(value = "w") final int w,@RequestParam(value = "h") final int h) throws Exception {
    Iterator<String> itr = fileIterator(request);
    multipartfile mpf = null;
    final FileMeta fileMeta = new FileMeta();
    // 2. get each file
    while (itr.hasNext()) {
        mpf = getmultipartfile(request,itr);
        checkIfEmpty(mpf);
        checkifValidFormat(mpf);

        final BufferedImage subImage = getBufImage(mpf).getSubimage(x1,y1,w,h);

        //final BufferedImage resizedImage = resizeImage(subImage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(subImage,mpf.getContentType().replace("image/",""),baos);
        final Account account = accountManager.findBySigin((String) request
                .getAttribute("account"));
        profilePictureService.saveProfilePicture(account.getId(),baos.toByteArray());

        prepareMetainformation(mpf,fileMeta,account,baos);
    }
    return fileMeta;
}

此代码适用于某些图像,但对大多数图像都不能正常工作.有没有人有任何线索.

例如,对于以下图像
它完美无缺,因为我完美地获得了裁剪后的图像.

但是对于这个图像
我没有正确获得裁剪的图像.

解决方法

我已经使用了下面的代码,它的工作对我来说..请通过下面的一个.

你的问题在这里:

setSelect: [0,

你传递的是不变的

jQuery(function ($) {

        // Create variables (in this scope) to hold the API and image size
        var jcrop_api,// Grab some information about the preview pane
            $preview = $('#preview-pane'),ysize = $pcnt.height();

        console.log('init',ysize]);
        $('#target').Jcrop({
            onChange: updatePreview,onSelect: updatePreview,onSelect: storeCoords,aspectRatio: xsize / ysize,BoxWidth: 350,BoxHeight: 350
        },function () {
            // Use the API to get the real image size
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            // Store the API in the jcrop_api variable
            jcrop_api = this;

            // Move the preview into the jcrop container for css positioning
            $preview.appendTo(jcrop_api.ui.holder);
        });

        function updatePreview(c) {
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = ysize / c.h;

                $pimg.css({
                    width: Math.round(rx * boundx) + 'px',height: Math.round(ry * boundy) + 'px',marginLeft: '-' + Math.round(rx * c.x) + 'px',marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
            // storeCoords(c);
        };
        function storeCoords(c) {

            jQuery('#X').val(c.x);
            jQuery('#Y').val(c.y);
            jQuery('#W').val(c.w);
            jQuery('#H').val(c.h);


        };

    });

请从您的代码中分离出此功能.

function storeCoords(c) {

        jQuery('#X').val(c.x);
        jQuery('#Y').val(c.y);
        jQuery('#W').val(c.w);
        jQuery('#H').val(c.h);


    };

并将调用storeCoords放在您之前设置的固定坐标处

setSelect:storeCoords,

javascript – mobx商店中的承诺

javascript – mobx商店中的承诺

我不确定如何在我的mobx商店实施承诺.我有两个动作,我想在循环中顺序运行,并确保在运行第二个之前等待第一个完成.这是我的商店代码示例.请询问任何进一步的说明,我一定要加上.我试图将代码简化为我认为找到解决方案所必需的内容.谢谢!

import { observable,action } from 'mobx';

import Store from '../support/store';

class Upload extends Store {
  @observable fileList = null;  // array of files to be uploaded
  @observable processedFile = null;  // single file pre-processed for upload

  @action processFile(file) {
    // takes file from fileList array,'processes' it and 
    // places the result in this.processedFile
  }

  @action post() {
    // makes a POST request,uploading this.processedFile
    // sets this.processedFile = null
  }

  @action postFileList() {
    // loops over the array this.fileList
    // runs this.processFile(file)
    // waits until processFile(file) is finished
    // runs post()
    // waits until post() is finished
    // removes file from the this.fileList array
  }
}

解决方法

如果您在操作中执行异步操作,则需要确保 wrap the asynchronously called function in an action as well.

你可以创建一个递归的postFileList,当fileList中没有剩下的文件时,它会退出.

class Upload extends Store {
  @observable fileList = [];
  @observable processedFile = null;

  @action processFile(file) {
    return new Promise(resolve => {
      const file = this.fileList[0];
      setTimeout(action(() => {
        this.processedFile = file.processed;
        resolve();
      }),1000); 
    });
  }

  @action post() {
    return new Promise(resolve => {
      const file = this.processedFile;
      setTimeout(action(() => {
        this.processedFile = null;
        resolve();
      }),1000); 
    });
  }

  @action postFileList() {
    if (this.fileList.length === 0) {
      return;
    }
    this.processFile()
      .then(() => this.post())
      .then(action(() => {
        this.fileList.shift();
        this.postFileList();
      }));
  }
}

javascript – Typescript:等待所有的承诺

javascript – Typescript:等待所有的承诺

我的承诺遇到了一个小问题.

这是我的功能:

public generateMealPlanForAWeek(myMealProfile: any, totalCalories:number):Promise<any> {
        return new Promise(resolve => {
            let mealplan:Array<any> = [];
            for (let i = 1; i <= 7; i++) {
                this.generateMealPlanForOneDay(myMealProfile, totalCalories).then(data => {
                    mealplan.push(data); // resolves much later
                });
            }
            resolve(mealplan); // is resolved instant
        })
    }

我的问题是,“generateMealPlanForOneDay”将在之后的膳食计划本身得到解决.

Mealplan是一系列物体(在这种情况下是用餐).

当我想保存我的膳食计划时,膳食计划是空的:

this.storage.set(''Mealplan'', JSON.stringify(mealplan)).then(....) // meal plan is Array[0]

什么是解决我的膳食计划的所有膳食然后保存它的最佳方法?

解决方法:

在这种情况下,您可以使用Promise.all.

public generateMealPlanForAWeek(myMealProfile: any, totalCalories:number):Promise<any> {
    var mealPlans = [];
    for (let i = 1; i <= 7; i++) {
       mealPlans.push(this.generateMealPlanForOneDay(myMealProfile, totalCalories));
    }
    return Promise.all(mealPlans);
}

// later
generateMealPlanForAWeek(...).then(mealPlans => ...);

总结

以上是小编为你收集整理的javascript – Typescript:等待所有的承诺全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

原文地址:https://codeday.me/bug/20190724/1523920.html

javascript – 为什么.json()会返回一个承诺?

javascript – 为什么.json()会返回一个承诺?

我最近一直在搞乱fetch()api,并注意到一些有点古怪的东西.

let url = "http://jsonplaceholder.typicode.com/posts/6";

let iterator = fetch(url);

iterator
  .then(response => {
      return {
          data: response.json(),
          status: response.status
      }
  })
  .then(post => document.write(post.data));
;

post.data返回一个Promise对象.
http://jsbin.com/wofulo/2/edit?js,output

但是如果写成:

let url = "http://jsonplaceholder.typicode.com/posts/6";

let iterator = fetch(url);

iterator
  .then(response => response.json())
  .then(post => document.write(post.title));
;

post这里是一个标准的Object,你可以访问title属性.
http://jsbin.com/wofulo/edit?js,output

所以我的问题是:为什么response.json在对象文字中返回一个promise,但是如果刚刚返回则返回值?

解决方法:

Why does response.json return a promise?

因为您在收到所有标题后立即收到回复.调用.json()可以获得尚未加载的http响应主体的另一个承诺.另见Why is the response object from JavaScript fetch API a promise?.

Why do I get the value if I return the promise from the then handler?

因为that’s how promises work.从回调中返回promises并使它们被采用的能力是它们最相关的特性,它使它们可以在没有嵌套的情况下进行链接.

您可以使用

fetch(url).then(response => 
    response.json().then(data => ({
        data: data,
        status: response.status
    })
).then(res => {
    console.log(res.status, res.data.title)
}));

或等待json身体后获得响应状态的任何其他approaches to access previous promise results in a .then() chain.

今天关于javascript – 有没有正确的方法来存储已解决的承诺?js的存储方式的介绍到此结束,谢谢您的阅读,有关javascript – Jcrop没有正确裁剪图像、javascript – mobx商店中的承诺、javascript – Typescript:等待所有的承诺、javascript – 为什么.json()会返回一个承诺?等更多相关知识的信息可以在本站进行查询。

本文标签: