没有回调的 JavaScript 原生 Promise() [英] JavaScript native Promise() without callback

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

问题描述

看看这个 jQuery 代码:

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.

在原生 JavaScript 中,我不能使用这种方法.构造函数 new Promise() 需要回调参数,所以我不能将 Promise 的实例作为参数传递.

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.

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

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   */);

它没有通过 some 本身,而是通过 resolvereject 函数.所以,依赖正好相反.

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天全站免登陆