理解Promise的三种姿式

译者按: 对于Promise,也许你会用了,却并不理解;也许你理解了,却只可意会不可言传。这篇博客将从3个简单的视角理解Promise,应该对你有所帮助。javascript

为了保证可读性,本文采用意译而非直译,而且对源代码进行了大量修改。另外,本文版权归原做者全部,翻译仅用于学习。html

示例1中,asyncFunc()函数返回的是一个Promise实例:java

// 示例1
function asyncFunc()
{
    return new Promise(function(resolve, reject)
    {
        setTimeout(function()
        {
            resolve('Hello, Fundebug!');
        }, 100);
    });
}

asyncFunc()
    .then(function(x)
    {
        console.log(x); // 1秒以后打印"Hello, Fundebug!"
    });

1秒以后,Promise实例的状态变为resolved,就会触发then绑定的回调函数,打印resolve值,即"Hello, Fundebug!"。node

那么,什么是Promise呢?es6

  • Promise调用是阻塞的
  • Promise中保存了异步操做结果
  • Promise是一个事件

Promise调用是阻塞的

示例2能够帮助咱们理解阻塞小程序

// 示例2
function asyncFunc()
{
    return new Promise(function(resolve, reject)
    {
        setTimeout(function()
        {
            resolve('Hello, Fundebug!');
        }, 1000);
    });
}

async function main()
{
    const x = await asyncFunc(); // (A)
    console.log(x); // (B) 1秒以后打印"Hello, Fundebug!"
}

main();

以上代码是采用Async/Await语法写的,与示例1彻底等价。await的中文翻译即为"等待",这里能够"望文生义"。所以,相比于使用Promise实现,它更加直观地展现了什么是阻塞微信小程序

  • (A)行: 等待asyncFunc()执行,直到它返回结果,并赋值给变量x
  • (B)行: 打印x

事实上,使用Promise实现时,也须要等待asyncFunc()执行,以后再调用then绑定的回调函数。所以,调用Promise时,代码也是阻塞的。数组

Promise中保存了异步操做结果

若是某个函数返回Promise实例,则这个Promise最初至关于一个空白的容器,当函数执行结束时,其结果将会放进这个容器。示例3经过数组模拟了这个过程:promise

// 示例3
function asyncFunc()
{
    const blank = [];
    setTimeout(function()
    {
        blank.push('Hello, Fundebug!');
    }, 1000);
    return blank;
}

const blank = asyncFunc();

console.log(blank);  // 打印"[]"

setTimeout(function()
{
    const x = blank[0]; // (A)
    console.log(x); // 2秒以后打印"Hello, Fundebug!"
}, 2000);

开始时,blank为空数组,1秒以后,"Hello, Fundebug!"被添加到数组中,为了确保成功,咱们须要在2秒以后从blank数组中读取结果。微信

对于Promise,咱们不须要经过数组或者其余变量来传递结果,then所绑定的回调函数能够经过参数获取函数执行的结果。

Promise是一个事件

示例4模拟了事件:

// 示例4
function asyncFunc()
{
    const eventEmitter = {
        success: []
    };

    setTimeout(function()
    {
        for (const handler of eventEmitter.success)
        {
            handler('Hello, Fundebug!');
        }
    }, 1000);

    return eventEmitter;
}

asyncFunc()
    .success.push(function(x)
    {
        console.log(x); // 1秒以后打印"Hello, Fundebug!"
    });

调用asyncFunc()以后,sucesss数组实际上是空的,将回调函数push进数组,至关于绑定了事件的回调函数。1秒以后,setTimeout定时结束,则至关于事件触发了,这时sucess数组中已经注册了回调函数,因而打印"Hello, Fundebug!"。

Promise成功resolve时,会触发then所绑定的回调函数,这其实就是事件。

参考

关于Fundebug

Fundebug专一于JavaScript、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了7亿+错误事件,获得了Google、360、金山软件、百姓网等众多知名用户的承认。欢迎免费试用!

版权声明

转载时请注明做者Fundebug以及本文地址:
https://blog.fundebug.com/2017/09/25/3-ways-to-understand-promise/

相关文章
相关标签/搜索