回调到异步等待

时间:2018-04-12 15:24:08

标签: javascript ecmascript-6 es6-promise

我一直在尝试使用此库:https://github.com/xkeshi/image-compressor

来自那里的例子:

new ImageCompressor(file, {
    quality: .6,
    success(result) {
      ...
    },
    error(e) {
      ...
    },
  });

我想将这个函数包装在一个名为compress的异步函数中,以便像使用它一样:

const compressed file = await compress(file)

2 个答案:

答案 0 :(得分:1)

private final class LoggingTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable task) {
        // web thread
        Map<String, String> webThreadContext = MDC.getCopyOfContextMap();
        return () -> {
            // work thread
            try {
                // TODO: is this thread safe?
                MDC.setContextMap(webThreadContext);
                task.run();
            } finally {
                MDC.clear();
            }
        };
    }

}

答案 1 :(得分:1)

您可以像这样简单地包装函数:

  function compress(parameters) {
      return new Promise((resolve,reject) => {
        new ImageCompressor(file, {
          quality: .6,
          success(result) {
            resolve(result)
          },
          error(e) {
            reject(e)
          },
        });
     })