JavaScript本机Promise()没有回调 [英] JavaScript native Promise() without callback

查看:189
本文介绍了JavaScript本机Promise()没有回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看这个jQuery代码:

  var promise = new Deferred(),
some;

some = function(promise){
//做酷事

promise.resolve();
};

promise.then(/ *回调酷东西* /);

// init everything
some(promise);

我不确定这种方法的架构是否正确,但我使用它很长时间,方便我



在本机JavaScript中,我无法使用这种方法。构造函数 new Promise()需要一个回调参数,所以我不能将 Promise 的实例作为参数传递。 p>

所以我的问题是:我如何预先定义JavaScript本机的承诺,将其作为参数传递给函数和解决方案?

解决方案

执行流程将会有所不同,但基本工作方式相同:

  function some(resolve,reject){
resolve();
}

var promise = new Promise(some);

promise.then(/ *回调酷东西* /);

而不是一些通过承诺本身,它通过解析拒绝函数。所以依赖是相反的。


Look at this jQuery code:

var promise = new Deferred(),
    some;

some = function(promise) {
    // do cool things

    promise.resolve();
};

promise.then(/*  callback cool things   */);

// init everything
some(promise);

I am not sure about architecture correctness of such approach, but I used it for long time and it is convenient for me.

In native JavaScript I can not use such approach. Constructor new Promise() requires a callback parameter, so I can not pass instance of Promise as a parameter.

So my question is: how can I predefine JavaScript native promise, pass it as a parameter to function and the resolve?

解决方案

The execution flow would be a little different, but basically work the same way:

function some(resolve, reject) {
    resolve();
}

var promise = new Promise(some);

promise.then(/*  callback cool things   */);

Instead of some getting passed the promise itself, it gets passed the resolve and reject functions. So, the dependency is just the other way round.

这篇关于JavaScript本机Promise()没有回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆